Converting Math.js-like Expressions to Runnable Python Code

36 Views Asked by At

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.

2

There are 2 best solutions below

1
cards On BEST ANSWER

SymPy has a in-build parser to translate a string into a SymPy expression. Use for ex subs or lambdify for evaluation.

Some further parsing rules can be passed via the transformations parameter such as implicit multiplication, i.e. 5x -> 5*x, here the full list.

from sympy import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

# tuple of transformations
transformations = (
    standard_transformations +
    (implicit_multiplication_application,))


s = '2*x^2 + 5x - 1'.replace('^', '**')
e = parse_expr(s, transformations=transformations)

# check object
print(e)
# 2*x**2 + 5*x - 1
print(type(e))
#<class 'sympy.core.add.Add'>
0
TheHungryCub On

You can convert the mathematical expression string into a SymPy expression, replace the ^ operator with ** (Python's exponentiation operator), and then create a Python function f(x) using lambdify.

from sympy import sympify, symbols, lambdify

x = symbols("x")
expression_str = "2*x^2 + 5*x - 1"
expression_sym = sympify(expression_str.replace("^", "**"))
f = lambdify(x, expression_sym, 'numpy')
print(f(2))  # Evaluate the function at x = 2

Output:

17