[英]Python eval expression all permutations for arithmetic operators
給定string = '1*7/5-3'
我有表達式來評估像eval('1*7/5-3')
這樣的字符串
代碼:
import __future__
string = '1*7/5-3'
print eval(compile(string, '<string>', 'eval', __future__.division.compiler_flag))
我想評估所有排列
example
eval('((1*7)/5)-3')
eval('1*((7/5)-3)')
and so on
我不應該對其進行編輯以消除“過分的”括號。 實際上,它們是必要的。 我正在恢復原始代碼。
想法是依次將每個運算符視為主要操作- 二進制表達式樹的根。 這將字符串分成兩部分,然后我們遞歸地應用該過程。
def parenthesize(string):
'''
Return a list of all ways to completely parenthesize operator/operand string
'''
operators = ['+','-','*','/']
depth = len([s for s in string if s in operators])
if depth == 0:
return [string]
if depth== 1:
return ['('+ string + ')']
answer = []
for index, symbol in enumerate(string):
if symbol in operators:
left = string[:index]
right = string[(index+1):]
strings = ['(' + lt + ')' + symbol +'(' + rt + ')'
for lt in parenthesize(left)
for rt in parenthesize(right) ]
answer.extend(strings)
return answer
string='4+7/5-3'
for t in parenthesize(string):print(t, eval(t))
此打印
(4)+((7)/((5-3))) 7.5
(4)+(((7/5))-(3)) 2.4
((4+7))/((5-3)) 5.5
((4)+((7/5)))-(3) 2.4000000000000004
(((4+7))/(5))-(3) -0.7999999999999998
順便說一句,這是針對Euler Project問題93的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.