parsing - Evaluating mathematical expressions in Python -
i want tokenize given mathematical expression parse tree this:
((3 + 4 - 1) * 5 + 6 * -7) / 2 '/' / \ + 2 / \ * * / \ / \ - 5 6 -7 / \ + 1 / \ 3 4
is there pure python way this? passing string python , tree mentioned above.
thanks.
yes, python ast
module provides facilities this. you'll have exact interface version of python, since ast
module seems change regularly.
in particular, ast.parse()
method helpful application:
>>> import ast >>> ast.parse("(1+2)*3", "", "eval") <_ast.expression object @ 0x88950> >>> ast.dump(_) 'expression(body=binop(left=binop(left=num(n=1), op=add(), right=num(n=2)), op=mult(), right=num(n=3)))'
Comments
Post a Comment