我不應該有edite它可以消除「無關」的括號。事實上,這是必要的。我正在恢復到原來的代碼。
這個想法是依次考慮每個運營商符號作爲主要操作 - binary expression tree的根。這將字符串分成兩部分,我們遞歸地應用這個過程。
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
BTW是這個歐拉項目問題93?
嘗試創建數值列表和操作列表。嘗試創建一個函數,以指定的順序評估操作時返回結果:my_eval(list_values,list_ops,order_ops)其中,order_ops = [1,2,3]是第一個示例,order_ops = [2,3,1 ]是你給出的第二個例子。似乎是一個遞歸的好候選 –