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:
def __init__(self):
self = []
def isEmpty(self):
return self == []
def push(self, item):
self.append(item)
def pop(self):
return self.pop(0)
def size(self):
return len(self)
s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print s
I corrected a few problems below. Also, a 'stack', in abstract programming terms, is usually a collection where you add and remove from the top, but the way you implemented it, you're adding to the top and removing from the bottom, which makes it a queue.
I left a comment with the link to http://docs.python.org/2/tutorial/datastructures.html#using-lists-as-stacks, but if you want to have a custom type that gives you
push
,pop
,is_empty
, andsize
convenience methods, I'd just subclasslist
.However, as I said in the comments, I'd probably just stick with a straight
list
here, as all you are really doing is aliasing existing methods, which usually only serves to make your code harder to use in the long run, as it requires people using it to learn your aliased interface on top of the original.Your problem is that you're popping from the beginning of the list, when you should be popping from the end of the list. A stack is a Last-In First-Out data structure, meaning that when you pop something from it, that something will be whatever you pushed on last. Take a look at your push function - it appends an item to the list. That means that it goes at the end of the list. When you call .pop(0), however, you're removing the first item in the list, not the one you last appended. Removing the 0 from .pop(0) should solve your problem.
The proper implementation would include
__iter__
also since Stack needs to be LIFO order.Assigning to
self
won't turn your object into a list (and if it did, the object wouldn't have all your stack methods any more). Assigning toself
just changes a local variable. Instead, set an attribute:and use the attribute instead of just a bare
self
:Also, if you want a stack, you want
pop()
rather thanpop(0)
.pop(0)
would turn your data structure into a(n inefficient) queue.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 addedstack.clear()
to empty a stack (like we have indeque.clear()
in collections module). I have also override__repr__
for debugging purpose:Here is how you can use it:
Primary, I implemented it to use to solve a programming problem next greater element.