Equation parsing in Python Equation parsing in Python python python

Equation parsing in Python


Python's own internal compiler can parse this, if you use Python notation.

If your change the notation slightly, you'll be happier.

import compilereq= "sin(x)*x**2"ast= compiler.parse( eq )

You get an abstract syntax tree that you can work with.


You can use Python parser:

import parserfrom math import sinformula = "sin(x)*x**2"code = parser.expr(formula).compile()x = 10print(eval(code))

It performs better than pure eval and, of course, avoids code injection!


 f = parser.parse('sin(x)*x^2').to_pyfunc()

Where parser could be defined using PLY, pyparsing, builtin tokenizer, parser, ast.

Don't use eval on user input.