【发布时间】:2017-07-27 13:54:34
【问题描述】:
我厌倦了运行这个程序,但它会在第 15 行给我上面的错误 该程序应该评估一个预序算术表达式,它从标准输入获取一个表达式并输出结果
return (preOrder( lst [ 1 : ( (len(lst)+1)/2) ] ) + preOrder( lst [ (len(lst) + 1)/2 : ] ))
这是我的程序
def preOrder(lst) :
if len(lst) == 3 :
if lst[0] == '+' :
return lst[1] + lst[2]
elif lst[0] == '-' :
return lst[1] - lst[2]
elif lst[0] == '*' :
return lst[1] * lst[2]
elif lst[0] == '/' :
return lst[1] / lst[2]
elif lst[0] == '%' :
return lst[1] % lst[2]
else :
if lst[0] == '+' :
return (preOrder( lst [ 1 : ( (len(lst)+1)/2) ] ) + preOrder( lst [ (len(lst) + 1)/2 : ] ))
elif lst[0] == '-' :
return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] ) - preOrder( lst [ (len(lst) + 1)/2 : ] )
elif lst[0] == '*' :
return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] ) * preOrder( lst [ (len(lst) + 1)/2 : ] )
elif lst[0] == '/' :
return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] ) / preOrder( lst [ (len(lst) + 1)/2 : ] )
elif lst[0] == '%' :
return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] ) % preOrder( lst [ (len(lst) + 1)/2 : ] )
pre = ['+', '+', 6, 3, '-', 8, 4]
print ("preorder:")
print (pre)
print (preOrder(pre))
【问题讨论】: