[英]Evaluating mathematical expressions in Python
我想將一個給定的數學表達式標記為一個解析樹,如下所示:
((3 + 4 - 1) * 5 + 6 * -7) / 2
'/'
/ \
+ 2
/ \
* *
/ \ / \
- 5 6 -7
/ \
+ 1
/ \
3 4
有沒有純Python方法來做到這一點? 就像將字符串作為字符串傳遞給Python然后像上面提到的那樣返回樹。
謝謝。
是的,Python ast
模塊提供了執行此操作的工具。 你必須查找你的Python版本的確切界面,因為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 ast模塊執行此操作。
https://docs.python.org/3.6/library/ast.html
操作是我們想要評估的數學運算,我們使用isinstance來了解它的類型,如果它是一個數字,如果它是一個二元運算符(+,*,..)。 你可以在https://greentreesnakes.readthedocs.io/en/latest/tofrom.html閱讀,如何工作
為了使方法有效,我們可以使用: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
我不知道采用“純python”的方式來實現這一點,這已經為你實現了。 但是你應該查看ANTLR(http://www.antlr.org/)這是一個開源解析器和詞法分析器,它有一個包含python在內的多種語言的API。 此網站還有一些很棒的視頻教程,可以向您展示如何正確地完成您的要求。 這是一個非常有用的工具,知道如何使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.