gpt4 book ai didi

python - 在 Python 中评估数学表达式

转载 作者:太空狗 更新时间:2023-10-29 18:02:39 25 4
gpt4 key购买 nike

我想将给定的数学表达式标记为这样的解析树:

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

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

是否有任何纯 Python 方法可以做到这一点?就像作为字符串传递给 Python,然后像上面提到的那样作为树返回。

谢谢。

最佳答案

是的,Python ast模块提供了执行此操作的工具。您必须查找适合您的 Python 版本的确切接口(interface),因为 ast 模块似乎会定期更改。

特别是 ast.parse()方法将有助于您的应用程序:

>>> 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)))'

关于python - 在 Python 中评估数学表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5049489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com