Why won't my list populate? IndexError: List Out of Range
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3
--
Chapters
00:00 Question
01:10 Accepted answer (Score 3)
02:54 Thank you
--
Full question
https://stackoverflow.com/questions/2012...
Question links:
[here]: http://interactivepython.org/courselib/s...
http://pastebin.com/dG4Ku14n
Accepted answer links:
[doubt]: https://stackoverflow.com/questions/2012...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #stack
#avk47
ACCEPTED ANSWER
Score 3
Unfortunately you operator_stack list is empty therefore it returns a IndexError BTW if you want to find the last element of a list use and make sure to make it to None if its empty:
So use:
peek = operator_stack[-1] if operator_stack else None
instead of:
peek = operator_stack[len(operator_stack)-1]
Also when debugging your code it is clearly visible from the comments that these lines in:
line 49 :while not operator_stack and prec[peek] >= prec[element]:
line 59 : while not operator_stack:
should actually look like:
line 49 :while operator_stack and prec[peek] >= prec[element]:
line 59 : while operator_stack:
Finally add a if statement to check if peek is None
A short version would be
#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())
If you doubt what while operator_stack: means, see this simple example:
>>> a = [2,5,6]
>>> while a: # a is not empty right?
... print 2 # so print 2
... break # and break
2