阅读Stacks,所以我尝试了这个Infix to Postfix练习(找到here)。你必须滚动一点才能看到他们的代码。我尽可能保持原始实现的真实性。
我的代码:http://pastebin.com/dG4Ku14n
我在第18行收到错误(我在其中定义了peek变量)。它说列表超出范围但我不应该调用列表吗?它不应该只存储在变量中,当我在第49行使用“prec [peek]”时,文档后面会出现实际错误吗?
我确信这段代码比我意识到的还要多。任何帮助,将不胜感激。我应该重新开始吗?
简短版本:
peek = operator_stack[len(operator_stack)-1]
for element in infix:
if:
#code
else:
while not operator_stack and prec[peek] >= prec[element]:
output_queue.append(operator_stack.pop())
operator_stack.append(element)
预期产出:
A B * C + D *
答案 0 :(得分:3)
不幸的是,您operator_stack
列表为空,因此如果您要查找列表使用的最后一个元素,则返回IndexError
BTW,如果其为空,请务必将其设为None
:
所以使用:
peek = operator_stack[-1] if operator_stack else None
而不是:
peek = operator_stack[len(operator_stack)-1]
同样在调试代码时,可以从以下注释中清楚地看到:
第49行:while not operator_stack and prec[peek] >= prec[element]:
第59行:while not operator_stack:
应该看起来像:
第49行:while operator_stack and prec[peek] >= prec[element]:
第59行:while operator_stack:
最后添加一个if语句来检查peek
是否为None
短版本将是
#line 18
peek = operator_stack[-1] if operator_stack else None
#line 49
if peek is not None:
while operator_stack and prec[peek] >= prec[element]:
#Append the pop'd element of the operator stack to the
#output_queue list.
output_queue.append(operator_stack.pop())
#Append whatever is left (+,-,*,/) to the operator stack
operator_stack.append(element)
#line 59
while operator_stack:
#Append the last element in the stack until the stack is empty.
output_queue.append(operator_stack.pop())
如果您doubt while operator_stack:
的含义,请参阅以下简单示例:
>>> a = [2,5,6]
>>> while a: # a is not empty right?
... print 2 # so print 2
... break # and break
2