I am pretty new to programming but I want to define a function like the following with user input:
function = raw_input('What function shall be used? ') #user puts in "(1+1/x)^x"
def f(x): #using this to define
y = (1+1/x)**x
return y
I hope it is clear what I try to do. Could you use input and define a priori that sin is used as math.sin? But how do I define the function afterwards?
Edited to add specification from the comments
Let's say the valid input is python code such as "(1+1/x)**x" like in the question. Could you now use eval to define a function f(x) which can be later used?
1 Answer 1
As I commented, this can be done with something like eval, but is unsafe because you should never trust random user input.
>>> def expr_to_fn(expr):
... expr = expr.replace('^', '**')
... symbols = set(re.findall(r'([A-Z,a-z]+)', expr))
... fn = eval("lambda {}: {}".format(",".join(symbols), expr))
... return fn
>>> f = expr_to_fn("(1+1/x)^x")
>>> f(2)
2.25
The safe way is to implenet a DSL and a parser, or use a CAS (computer algebra system) like sympy, as suggested by Hiro.
4 Comments
sin, cos and the like. However, this does make me understand what you meant by using a context dictionary, which could probably take this the rest of the way there.Explore related questions
See similar questions with these tags.
evalbecauseevalevaluates a python expression, but(1+1/x)^xdoes not mean(1+1/x)**xin python.eval()but don't... It's very unsafe and your users would need to know at least a bit of Python (e.g. something to the power of something else is defined as**not^) - and if they do, why not let them define their own modules that your app will load instead of requiring them to manually type math formulas?