Evaluating mathematical expressions in Python

前端 未结 5 1282
小鲜肉
小鲜肉 2020-12-17 18:24

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

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

                          \'/\'
                      


        
5条回答
  •  情书的邮戳
    2020-12-17 19:04

    There are many good, established algorithms for parsing mathematical expressions like this one. One particularly good one is Dijkstra's shunting-yard algorithm, which can be used to produce such a tree. I don't know of a particular implementation in Python, but the algorithm is not particularly complex and it shouldn't take too long to whip one up.

    By the way, the more precise term for the tree you're constructing is a parse tree or abstract syntax tree.

提交回复
热议问题