Christian Singer Christian Singer - 9 days ago 6
Python Question

Parsing a string input into a lambda function (Python)

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.

Answer

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.

Comments