I am trying to implement a simple stack with Python using arrays. I was wondering if someone could let me know what\'s wrong with my code.
class myStack:
I would like to share my version of the stack implementation that inherits Python List. I believe iteration on a stack should be happening in LIFO order. Additionally, an iteration on pop-all()
should be provided to iterate while poping all elements. I have also added stack.clear()
to empty a stack (like we have in deque.clear() in collections module). I have also override __repr__
for debugging purpose:
class Stack(list):
def push(self, item):
self.append(item)
def top(self):
return self[-1]
def size(self):
return len(self)
def isempty(self):
return self.size() == 0
def __iter__(self):
""" iter in lifo """
return super(Stack, self).__reversed__()
def __reversed__(self):
return super(Stack, self).__iter__()
def popall(self):
try:
while True:
yield self.pop()
except IndexError:
pass
def clear(self):
del self[:]
def __repr__(self):
if not self:
return '%s()' % self.__class__.__name__
return '%s(%s)' % (self.__class__.__name__, super(Stack, self).__repr__())
Here is how you can use it:
stack = Stack(range(5))
print "stack: ", stack # stack: Stack([0, 1, 2, 3, 4])
print "stack.pop() => ", stack.pop() # stack.pop() => 4
print "stack.push(20) " # stack.push(20)
stack.push(20)
for item in stack:
print item # prints 20, 3, 2... in newline
print "stack: ", stack # stack: Stack([0, 1, 2, 3, 20])
print "stack pop all..."
for item in stack.popall(): # side effect to clear stack
print item
print "stack: ", stack # stack: Stack()
Primary, I implemented it to use to solve a programming problem next greater element.