Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equation parsing in Python

How can I (easily) take a string such as "sin(x)*x^2" which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of x?

like image 518
WalkingRandomly Avatar asked Feb 27 '09 10:02

WalkingRandomly


1 Answers

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

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

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

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

like image 103
S.Lott Avatar answered Oct 21 '22 03:10

S.Lott