我正在尝试使用 Python 计算后缀表达式,但没有成功。我认为这可能是与 Python 相关的问题。
有什么建议么?
expression = [12, 23, 3, '*', '+', 4, '-', 86, 2, '/', '+']
def add(a,b):
return a + b
def multi(a,b):
return a* b
def sub(a,b):
return a - b
def div(a,b):
return a/ b
def calc(opt,x,y):
calculation = {'+':lambda:add(x,y),
'*':lambda:multi(x,y),
'-':lambda:sub(x,y),
'/':lambda:div(x,y)}
return calculation[opt]()
def eval_postfix(expression):
a_list = []
for one in expression:
if type(one)==int:
a_list.append(one)
else:
y=a_list.pop()
x= a_list.pop()
r = calc(one,x,y)
a_list = a_list.append(r)
return content
print eval_postfix(expression)
原文由 newlife 发布,翻译遵循 CC BY-SA 4.0 许可协议
只需将
a_list = a_list.append(r)
替换为a_list.append(r)
。Most functions, methods that change the items of sequence/mapping does return
None
:list.sort
,list.append
,dict.clear
…没有直接关系,但请参阅 为什么 list.sort() 不返回排序列表? .