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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.