Skip to content Skip to sidebar Skip to footer

String In List, Into A Function

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 interpr

Solution 1:

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

Solution 2:

You're confusing a string value with executable code. Two basic points:

  1. You can do this with the eval function, which evaluates a string as Python code.
  2. Don't. Really; eval is a loaded gun pointed at your foot, and usually indicates a poor system design.

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":
    returnsin(x)
elif choice == "cos":
    returncos(x)
...

Solution 3:

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:

deff(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:

deff(x):
    return math_dict[x] if x in math_dict elseNone

Solution 4:

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')

Solution 5:

With sympy.sympify and highlighting the warning

Warning : sympify uses eval. 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 functiondeff(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

Post a Comment for "String In List, Into A Function"