5

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.

3
  • 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. Commented Nov 27, 2016 at 12:29
  • fx will always be str, unless you're using Python 2.x. Commented Nov 27, 2016 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 Commented Nov 27, 2016 at 12:34

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.