I want to tokenize a given mathematical expression into a parse tree like this:
((3 + 4 - 1) * 5 + 6 * -7) / 2
\'/\'
You can do this with the Python ast module.
https://docs.python.org/3.6/library/ast.html
theoperation is our mathematical operation we want to evaluate, we use the isinstance in order to know the type it is, if its a number, if its a binary operator(+,*,..). You can read at https://greentreesnakes.readthedocs.io/en/latest/tofrom.html , how the ast work
And in order to make the method work we sould use: evaluate(ast.parse(theoperation, mode='eval').body)
def evaluate(theoperation):
if (isinstance(theoperation, ast.Num)):
return theoperation.n
if (isinstance(theoperation, ast.BinOp)):
leftope= evaluate(theoperation.left)
rightope=evaluate(theoperation.right)
if (isinstance(theoperation.op, ast.Add)):
return left+right
elif (isinstance(theoperation.op, ast.Sub)):
return left-right
elif (isinstance(theoperation.op, ast.Mult)):
return left*right
elif (isinstance(theoperation.op, ast.Div)):
return left/right
elif (isinstance(theoperation.op, ast.Pow)):
return left**right