[英]Getting mathematical function as user's input
I need to know how transfer string input into executable function.我需要知道如何将字符串输入转换为可执行函数。 For example - user write string 'x*Sin(x**2)' and then programm takes it as function, can calculate a value for given x, can plot derivation of this function etc. I've read that there is module called scitools.stringfunction, but as far as I know this module is not callable in python-3.
例如 - 用户写入字符串 'x*Sin(x**2)' 然后编程将其作为函数,可以计算给定 x 的值,可以绘制该函数的推导等。我读过有一个模块被调用scitools.stringfunction,但据我所知,这个模块在 python-3 中是不可调用的。
Any ideas how to make it?任何想法如何制作?
f = lambda x: input() # the user inputs: x**2 + 1
y = f(3)
print y # outputs: 10
f = lambda x: eval(input())
y = f(5)
print y
Just make sure to import
the required mathematical functions.只需确保
import
所需的数学函数即可。 And make sure the user inputs a valid Python arithmetic expression.并确保用户输入有效的 Python算术表达式。
using sympy you could do something like this:使用sympy你可以做这样的事情:
from sympy import var
from sympy import sympify
x = var('x') # the possible variable names must be known beforehand...
user_input = 'x * sin(x**2)'
expr = sympify(user_input)
res = expr.subs(x, 3.14)
print(res) # -1.322...
if you want to turn the user input into a function you can call you could to this:如果你想把用户输入变成一个函数,你可以调用你可以这样:
from sympy.utilities.lambdify import lambdify
f = lambdify(x, expr)
# f(3.14) -> -1.322...
sympy can do sybolic calculations (including derivatives); sympy 可以进行符号计算(包括导数); if you want to make plots i strongly suggest
matplotlib
.如果你想
matplotlib
我强烈建议matplotlib
。
the advantage of using a math library opposed to eval
is that you do not need to sanitize the user input (against malicious code).使用数学库而不是
eval
的优点是您不需要清理用户输入(针对恶意代码)。
(deleted this thanks to a comment from ejm ). (由于ejm的评论删除了这个)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.