I'm writing a program that involves calculating the maximum of a user defined function, however if the user enters a function in terms of a variable such as x, i.e.
input = x**2 + 2*x + 1
I (fairly expectedly) get an error as x is not defined.
Does anyone know of an effective way to allow a user to input a function in terms of a single variable such as x?
-
Look here: stackoverflow.com/questions/594266/equation-parsing-in-pythonKCH– KCH2011年12月12日 21:48:28 +00:00Commented Dec 12, 2011 at 21:48
-
int(raw_input("please enter x")) docs.python.org/library/functions.html#raw_inputbpgergo– bpgergo2011年12月12日 21:48:56 +00:00Commented Dec 12, 2011 at 21:48
1 Answer 1
If you are not worried about security much, simplest solution is to eval the expression e.g.
def calculate(value, function):
x = value
return eval(function)
print calculate(2, "x**2 + 2*x + 1")
print calculate(2, "x**3 - x**2 + 1")
output:
9
5
You can make it more secure by passing an empty builtin dict but still I think some clever code will be able to access internals of your code.
4 Comments
int(raw_input(...)) strategy @bpgergo suggested.x value and function string from user e.g. from gui or command-line or from an API