Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math Expression Evaluation

What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.

clarification: I need something slightly more advanced than eval() - I want to be able to add other operators (for example a maximum operator - 4$2 = 4) or, also I am more interested in this academically than professionaly - I want to know how to do this.

like image 552
Ori Shavit Avatar asked Oct 09 '09 18:10

Ori Shavit


3 Answers

If you're "academically interested", you want to learn about how to write a parser with operator precedence.

Simple Top-Down Parsing in Python is a nice article that builds an example parser to do exactly what you want to do: Evaluate mathematical expressions.

I can highly recommend having a go at writing your own first parser -- it's one of those "ah, that's how that works" moments!

like image 116
Martin B Avatar answered Oct 21 '22 19:10

Martin B


Another possibility is to look at Pyparsing, which is a general parser builder. It is more powerful than you need, but it may be faster to implement.

like image 21
Kathy Van Stone Avatar answered Oct 21 '22 19:10

Kathy Van Stone


I'm not terribly familiar with Python and any extremely Pythonic methods, but you could look at the Interpreter pattern, which is defined in the Gang of Four book. It's designed for processing a "language", and mathematical expressions do follow a particular language with rules. In fact, the example on Wikipedia is actually a Java implementation of a RPN calculator.

like image 38
Thomas Owens Avatar answered Oct 21 '22 19:10

Thomas Owens