如何将令牌变成树木(Python)
我正在研究一个Python项目,当您用方程式(包括操作员)的一行编写时,它将为您计算方程式。 首先,如果我们在字符串中写入,它将将字符串转换为单个令牌。
"12+2*3" -> [ "12", "+", "2", "*", "3" ]
然后,我们将每个令牌更改为一棵树。
[ "12", "+", "2", "*", "3" ]
- > [[“ 12”],“+”,[[“ 2”],“*”,[3']]]]
[ "(", "2", "+", "3", ")", "*", "7" ]
- > [[[[[“ 2”),“+”,[“ 3”]],“(”,[,[],“*”,[7']]
代币必须按列表按操作顺序分组,如果有par虫,它一定是[[parantheses内部的数字],“(”,[,[]]
我在第二部分中遇到麻烦,将令牌覆盖成树。建议我使用一个递归功能,但是如何呢?
I'm working on a python project which when you write in a line of an equation(including operators) it will calculate the equation for you.
First, if we write in a string, it would convert the string into individual tokens.
"12+2*3" -> [ "12", "+", "2", "*", "3" ]
Then, we would change each token into a tree.
[ "12", "+", "2", "*", "3" ]
-> [ ["12"], "+", [["2"], "*", ["3"]] ]
[ "(", "2", "+", "3", ")", "*", "7" ]
->
[[[["2"], "+", ["3"]], "(", []], "*", ["7"]]
Tokens must be grouped by a list in the order of operations, and if there are parantheses, it must be in the form of [[The number inside the parantheses], "(", []]
I am having trouble with the second part, coverting tokens into trees. It is recommended that I use a recursive function, but how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您可以使用的实现:
Here is an implementation you could use: