Getting mathematical function as user's input

2019-06-06 13:26发布

问题:

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.

Any ideas how to make it?

回答1:

For Python 2.X

f = lambda x: input() # the user inputs: x**2 + 1
y = f(3)
print y # outputs: 10

For Python 3.X

f = lambda x: eval(input())
y = f(5)
print y

Just make sure to import the required mathematical functions. And make sure the user inputs a valid Python arithmetic expression.



回答2:

using sympy you could do something like this:

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); if you want to make plots i strongly suggest 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).