Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating mathematical expressions in Python

I want to tokenize a given mathematical expression into a parse tree like this:

((3 + 4 - 1) * 5 + 6 * -7) / 2

                          '/'
                        /     \
                       +        2
                    /     \
                  *         *
                /   \     /   \
               -     5   6     -7
             /   \
            +     1
          /   \
         3     4

Is there any pure Python way to do this? Like passing as a string to Python and then get back as a tree like mentioned above.

Thanks.

like image 603
vander Avatar asked Feb 19 '11 07:02

vander


1 Answers

Yes, the Python ast module provides facilities to do this. You'll have to look up the exact interface for your version of Python, since the ast module seems to change regularly.

In particular, the ast.parse() method will be helpful for your application:

>>> import ast
>>> ast.parse("(1+2)*3", "", "eval")
<_ast.Expression object at 0x88950>
>>> ast.dump(_)
'Expression(body=BinOp(left=BinOp(left=Num(n=1), op=Add(), right=Num(n=2)), op=Mult(), right=Num(n=3)))'
like image 118
Greg Hewgill Avatar answered Sep 29 '22 13:09

Greg Hewgill