I’m working on an infix to prefix program utilizing a stack class. However, the push() method is raising an IndexError whenever I call an integer, even though I have an Exception Handler and I’m referencing the integer itself, not a list.
stack.py:
class stack():
def __init__(self,n):
self.n = n
self.top = -1
self.stack = [""] * n
#...
def push(self,c):
try:
print(self.top)
self.top += 1
self.stack[self.top] = c
except IndexError:
print("Stack is full.")
pip.py:
def toPrefix(input):
instack = stack(15)
prefix = ""
for i in range(0,len(input)):
for c in range(0,len(input[i])):
if(input[i][c].isalpha()):
instack.push(input[i][c])
Error:
Traceback (most recent call last):
File "<string>", line 247, in run_nodebug
File "P:\Scripts\Python\ascl-pip.py", line 42, in <module>
toPrefix(infix)
File "P:\Scripts\Python\ascl-pip.py", line 37, in toPrefix
instack.push(input[i][c])
File "P:\Scripts\Python\stack.py", line 36, in push
print(self.top)
IndexError: list assignment index out of range
Your traceback is inconsistent. It claims the line
is the reason for the
IndexError, butprint()will never raise such an error.The only way this can happen is that you are using an old version of your module that is still loaded in an interpreter instance. Restart your interpreter.
If you really need to implement your own stack class, you could go with something stupid like this:
This stack will have an unlimited size.