用Python评估数学表达式 [英] Evaluating mathematical expressions in Python

查看:161
本文介绍了用Python评估数学表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

Is there any pure Python way to do this? Like passing as a string to Python and then get back as a tree like mentioned above.

谢谢.

推荐答案

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

Yes, the Python ast module provides facilities to do this. You'll have to look up the exact interface for your version of Python, since the ast module seems to change regularly.

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

In particular, the ast.parse() method will be helpful for your application:

>>> 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评估数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆