Im trying to convert a string I got from math.js (for example 2*x^2+5x-1 ) to a runnable python function that looks something like this:
def f(x):
return 2*(x**2)+5*x-1
I've experimented with sympify from the sympy module:
from sympy import sympify, symbols
x = symbols("x")
expression = "x**2 + 3*x-1"
print(sympify(expression).subs(x, 2))
However, this approach fails to handle certain operations like ^ and only returns the result. Additionally, I've tried using the eval() function, encountering similar issues.
SymPy has a in-build parser to translate a string into a SymPy expression. Use for ex
subsorlambdifyfor evaluation.Some further parsing rules can be passed via the
transformationsparameter such as implicit multiplication, i.e.5x->5*x, here the full list.