[英]How to convert an user-input into a function in python 2.7
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 ?
您可以使用输入并定义先验将sin用作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. 假设问题中的有效输入是python代码,例如“(1 + 1 / x)** x”。 Could you now use
eval
to define a function f(x)
which can be later used? 您现在可以使用
eval
定义函数f(x)
以便以后使用吗?
As I commented, this can be done with something like eval
, but is unsafe because you should never trust random user input. 正如我所评论的那样,可以使用
eval
类的方法来完成此操作,但这是不安全的,因为您永远都不应信任随机的用户输入。
>>> 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. 如Hiro所建议的,安全的方法是实现DSL和解析器,或使用诸如sympy之类的CAS(计算机代数系统)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.