2013-11-21 54 views
4

閱讀堆棧,所以我嘗試了這個中綴到Postfix練習(找到here)。你必須滾動一下才能看到他們的代碼。我試圖儘可能保持原來的實現。爲什麼我的列表不會填充? IndexError:列表超出範圍

我的代碼:http://pastebin.com/dG4Ku14n

我得到第18行(這裏我定義偷看變量)的錯誤。它說列表超出範圍,但我不應該打電話給名單呢?不應該只是將它存儲在變量中,而當我在第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 * 
+2

請降低代碼爲[短,自足的,正確的示例](http://sscce.org/ )並將其直接包含到問題中。 –

+0

請發佈您的預期輸出 –

+0

增加了預期的輸出 –

回答

3

不幸的是你,如果你想找到的名單使用的最後一個元素,使operator_stack列表因此空的,它返回一個IndexError BTW如果它爲空,請務必將其設置爲None

如此使用:

peek = operator_stack[-1] if operator_stack else None

代替:

peek = operator_stack[len(operator_stack)-1]

而且調試代碼時,它是從註釋中清楚地看到,這些行:

線49while not operator_stack and prec[peek] >= prec[element]:

line 59while not operator_stack:

實際上應該是這樣的:

線49while operator_stack and prec[peek] >= prec[element]:

線59while operator_stack:

最後添加一個if語句來檢查,如果peekNone

簡短版本將是

#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 
+1

沒有幫助,因爲堆棧是空的 –

+0

@MarkRansom剛注意到 –

+0

'peek =(operator_stack [-1:] + [None])[0]'? –

相關問題