2

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?

2 Answers2

5

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.

5

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).
(deleted this thanks to a comment from ejm).

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • 1
    This is not true: as of posting, `sympify` is not sanitizing user input and is just passing to `eval` internally. See https://github.com/sympy/sympy/issues/10805. It has high priority label and last activity on this was January 2020 so we might see some change in this. So in other words, be careful with untrusted input using `sympify` same as you would using `eval`. – ejm Jun 11 '20 at 02:41