如何将用户输入转换为python 2.7中的函数 [英] How to convert an user-input into a function in python 2.7

查看:49
本文介绍了如何将用户输入转换为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

我希望我清楚该做什么.您可以使用输入并定义将 sin 用作 math.sin 的先验条件?但是我该如何定义函数呢?

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?

已编辑以添加评论中的规范

假设问题中的有效输入是python代码,例如(1 + 1/x)** x".您现在可以使用 eval 定义一个函数 f(x)以便以后使用吗?

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?

推荐答案

正如我所评论的,可以使用 eval 之类的方法来完成此操作,但是这是不安全的,因为您永远都不应信任随机的用户输入./p>

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

按照Hiro的建议,安全的方法是实现DSL和解析器,或者使用诸如sympy之类的CAS(计算机代数系统).

The safe way is to implenet a DSL and a parser, or use a CAS (computer algebra system) like sympy, as suggested by Hiro.

这篇关于如何将用户输入转换为python 2.7中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆