Reputation: 11
myList = ['100', 'sin(x)', '0', '1']
I read these strings from a text file. I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.
I have tried the following with no success.
myList[1].replace("'", "")
I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.
The end goal is to get this function, where myList[1] should turn to sin(x)
from math import sin
def f(x):
return myList[1]
Thus f(x) will give the computed value of sin(x) from this list.
Upvotes: 0
Views: 113
Reputation: 25992
With sympy.sympify and highlighting the warning
Warning :
sympify
useseval
. Don’t use it on unsanitized input.
you can solve this as
myList = ['100', 'sin(x)', '0', '1']
from sympy.abc import x
from sympy import sympify
N, expr, a,b = myList
# convert strings to objects
N=int(N); a=float(a); b=float(b);
expr = sympify(expr)
# define user function
def f(xval): return expr.subs(x,xval)
or for multi-point evaluation replace the last line with
from sympy import lambdify
f = lambdify(x, expr, "numpy")
# integrate as left Riemann sum (order 1)
from numpy import linspace
xlist = linspace(a,b,N)
integral = sum(f(xlist))*(b-a)/N
Upvotes: 0
Reputation: 1405
Sin function is part of math library, you can get it like:
import math
getattr(math, 'sin')
That is same for all non-builtin libraries. Just split the string to get function name:
function_name = myList[1].split('(')[0]
function = getattr(math, function_name)
function(value for x)
For builtin functions like round:
getattr(globals()['__builtins__'], 'round')
Upvotes: 1
Reputation:
The safest way I can see to do this is to store the expected functions in a dictionary like this:
math_dict = {'sin(x)':sin, 'cos(x)':cos}
then you can call sin from the list like this:
def f(x):
return math_dict[myList[1]](x)
I just added cos(x) to show you can do this with any arbitrary function. You could then do something like this to generalize it:
def f(x):
return math_dict[x] if x in math_dict else None
Upvotes: 1
Reputation: 77857
You're confusing a string value with executable code. Two basic points:
What is it that you're trying to do overall? If you want to trigger the trig functions with text input, you're better heeled to do it with enumerated checks, such as:
choice = myList[1]
if choice == "sin":
return sin(x)
elif choice == "cos":
return cos(x)
...
Upvotes: 2
Reputation: 6121
use dict and you archive it
from math import sin
myList = ['100', 'sin(x)', '0', '1']
options = { 'sin(x)':sin }
options[myList[1]](1)
0.8414709848078965
Upvotes: 3