Christian Singer - 11 months ago 72

Python Question

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`

Answer Source

First things first, `input()`

behaves differently in Python 2 and Python 3, as specified in this answer.

`eval()`

is one of the simplest options:

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

```
>>> 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.