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.
class myStack:
def __init__(self):
self.container = [] # You don't want to assign [] to self - when you do that, you're just assigning to a new local variable called `self`. You want your stack to *have* a list, not *be* a list.
def isEmpty(self):
return self.size() == 0 # While there's nothing wrong with self.container == [], there is a builtin function for that purpose, so we may as well use it. And while we're at it, it's often nice to use your own internal functions, so behavior is more consistent.
def push(self, item):
self.container.append(item) # appending to the *container*, not the instance itself.
def pop(self):
return self.container.pop() # pop from the container, this was fixed from the old version which was wrong
def peek(self):
if self.isEmpty():
raise Exception("Stack empty!")
return self.container[-1] # View element at top of the stack
def size(self):
return len(self.container) # length of the container
def show(self):
return self.container # display the entire stack as list
s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print(s.show())
Answer from Brionius on Stack OverflowI 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.
class myStack:
def __init__(self):
self.container = [] # You don't want to assign [] to self - when you do that, you're just assigning to a new local variable called `self`. You want your stack to *have* a list, not *be* a list.
def isEmpty(self):
return self.size() == 0 # While there's nothing wrong with self.container == [], there is a builtin function for that purpose, so we may as well use it. And while we're at it, it's often nice to use your own internal functions, so behavior is more consistent.
def push(self, item):
self.container.append(item) # appending to the *container*, not the instance itself.
def pop(self):
return self.container.pop() # pop from the container, this was fixed from the old version which was wrong
def peek(self):
if self.isEmpty():
raise Exception("Stack empty!")
return self.container[-1] # View element at top of the stack
def size(self):
return len(self.container) # length of the container
def show(self):
return self.container # display the entire stack as list
s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print(s.show())
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 to self just changes a local variable. Instead, set an attribute:
def __init__(self):
self.stack = []
and use the attribute instead of just a bare self:
def push(self, item):
self.stack.append(item)
Also, if you want a stack, you want pop() rather than pop(0). pop(0) would turn your data structure into a(n inefficient) queue.
Implement a stack class in Python - Code Review Stack Exchange
how to use the Stack()?
Discussing and Implementing a Stack in Python
I don't understand how Python 3 uses stacks in recursion.
Videos
Thanks for sharing your code,
instead of using size, you should implement __len__, this way you can use len(my_stack).
def __len__(self):
return len(self.item)
I think a method that prints an element from a collection is a bit unusual. What I would expect is a method called peek that returns the top element but doesn't remove it. By just printing it you're limiting its use to console only applications, and the only way to retrieve the element is to remove it!
You should consider adding an error message to go with your IndexError, and maybe reconsider the exception type, an IndexError sounds like you're accessing an index, but you're not maybe a custom StackEmpty exception would be more suitable.
I think self.item should be self.items (plural) as it will be representing zero or more items.
Bonus Stuff
you could implement the __iter__ method. This would allow the caller to do something like
for element in my_stack:
do_stuff()
You code is also missing docstrings, you could optionally add those to document your code.
You could implement the __str__ method to provide a nice string representation so you can simply say
print my_stack
Hopefully you found this helpful, keep it up!
You can simplify your top function like the code below.
def top(self):
if self.item: # if len > 0 it will evaluate to True
print self.item[-1] # -1 refer to the last item
else :
print "Empty list"