Why is my list not filling out? IndexError: List Out of Range

Reading on Stacks, so I tried this Infix exercise for Postfix (found here ). You will have to scroll a bit to see their code. I tried to stick to their initial implementation as soon as possible.

My code: http://pastebin.com/dG4Ku14n

I get an error on line 18 (where I define the peek variable). He says the list is out of range, but I shouldn't have called that list yet? Shouldn't it just be stored in a variable, and the actual error should happen later in the document when I use "prec [peek]" on line 49?

I am sure this code is more fubar than I understand. Any help would be greatly appreciated. Should I start?

Short version:

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 *
+4
1

, 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())

, while operator_stack:, . :

>>> a = [2,5,6]
>>> while a: # a is not empty right?
...     print 2 # so print 2
...     break # and break
2
+3

All Articles