【发布时间】:2013-11-16 09:22:57
【问题描述】:
我正在尝试使用 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)
【问题讨论】:
-
与您的问题完全无关,但 1/ 您可能需要阅读
operator模块的文档,以及 2/ 在您的calc函数中您根本不需要 lambda - 只需映射到运算符函数并在调用时传递参数,即:{"+": add, "-":sub,}[opt](x, y)。这也将允许您在全局范围内定义映射,从而避免在每次调用calc时一次又一次地构建它。 -
@brunodesthuilliers,谢谢,太好了!!!
标签: python