4

How can I parse a string input into the proper form for it to be executed as mapping regulation in a lambda function?

 fx=type(input("Enter a polynomial: "))

This is my input, I want to enter arbirtray polynomials.

f= lambda x: fx

Now i want my lambda function to be able to execute the strings from the input function just as if they were normal mapping regulations like x**2 for instance.

Christian Singer
  • 295
  • 3
  • 5
  • 15
  • Your question is not clear. Do you mean you want to input a string that represents a polynomial and store it in variable `fx`, then parse it into a new string format that can be evaluated more easily? Or do you want a function that evaluates that string and can be used in another, lambda function? Or something else? I hope you realize that your lambda expression as written is meaningless. – Rory Daulton Nov 27 '16 at 12:29
  • `fx` will always be `str`, unless you're using Python 2.x. – jonrsharpe Nov 27 '16 at 12:32
  • Yes, i would like to do the second option. The expression is part of a bigger program, this is only the part that causes me my problem – Christian Singer Nov 27 '16 at 12:34

1 Answers1

8

First things first, input() behaves differently in Python 2 and Python 3, as specified in this answer.

eval() is one of the simplest options:

Python 3

>>> fx = input("Enter a polynomial: ")
Enter a polynomial: x**2 + 2*x + 1
>>> f = lambda x: eval(fx)
>>> f(1)
4

Python 2

>>> fx = raw_input("Enter a polynomial: ")
Enter a polynomial: x**2 + 2*x + 1
>>> f = lambda x: eval(fx)
>>> f(1)
4

Be careful though, as eval() can execute arbitrary code.

Community
  • 1
  • 1
farsil
  • 955
  • 6
  • 19