Skip to content Skip to sidebar Skip to footer

Implementing Stack With Python

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):

Solution 1:

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.

classmyStack:
     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.defisEmpty(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.defpush(self, item):
         self.container.append(item)  # appending to the *container*, not the instance itself.defpop(self):
         return self.container.pop()  # pop from the container, this was fixed from the old version which was wrongdefpeek(self):
         if self.isEmpty():
             raise Exception("Stack empty!")
         return self.container[-1]  # View element at top of the stackdefsize(self):
         returnlen(self.container)  # length of the containerdefshow(self):
         return self.container  # display the entire stack as list


s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print(s.show())

Solution 2:

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:

defpush(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.

Solution 3:

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, and size convenience methods, I'd just subclass list.

classStack(list):defpush(self, item):
        self.append(item)
    defsize(self):
        return len(self)
    defis_empty(self):
        returnnotself

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.

Solution 4:

A stack is a container (linear collection) in which dynamic set operations are carried out as per the last-in first-out (LIFO) principle. There is only one pointer - top, which is used to perform these operations

CLRS implementation of stack using array:

classStack:
    """
    Last in first out (LIFO) stack implemented using array.
    """def__init__(self, capacity=4):
        """
        Initialize an empty stack array with default capacity of 4.
        """
        self.data = [None] * capacity
        self.capacity = capacity
        self.top  = -1defis_empty(self):
        """
        Return true if the size of stack is zero.
        """if self.top == -1:
            returnTruereturnFalsedefpush(self, element):
        """
        Add element to the top.
        """
        self.top += 1if self.top >= self.capacity:
            raise IndexError('Stack overflow!')
        else:
            self.data[self.top] = element

    defpop(self):
        """
        Return and remove element from the top.
        """if self.is_empty():
            raise Exception('Stack underflow!')
        else:
            stack_top = self.data[self.top]
            self.top -= 1return stack_top

    defpeek(self):
        """
        Return element at the top.
        """if self.is_empty():
            raise Exception('Stack is empty.')
            returnNonereturn self.data[self.top]

    defsize(self):
        """
        Return the number of items present.
        """return self.top + 1

Testing the implemetation:

defmain():
    """
    Sanity test
    """
    stack = Stack()

    print('Size of the stack is:', stack.size())
    stack.push(3)
    print('Element at the top of the stack is: ', stack.peek())
    stack.push(901)
    print('Element at the top of the stack is: ', stack.peek())
    stack.push(43)
    print('Element at the top of the stack is: ', stack.peek())
    print('Size of the stack is:', stack.size())
    stack.push(89)
    print('Element at the top of the stack is: ', stack.peek())
    print('Size of the stack is:', stack.size())
    #stack.push(9)    # Raises IndexError
    stack.pop()
    print('Size of the stack is:', stack.size())
    stack.pop()
    print('Size of the stack is:', stack.size())
    stack.pop()
    print('Size of the stack is:', stack.size())
    print('Element at the top of the stack is: ', stack.peek())
    stack.pop()
    #print('Element at the top of the stack is: ', stack.peek())    # Raises empty stack exceptionif __name__ == '__main__':
    main()

Solution 5:

The proper implementation would include __iter__ also since Stack needs to be LIFO order.

classStack:
    def__init__(self):
        self._a = []

    defpush(self, item):
        self._a.append(item)

    defpop(self):
        return self._a.pop()

    defisEmpty(self):
        returnlen(self._a) == 0def__iter__(self):
        returnreversed(self._a)

    def__str__(self):
        # return str(list(reversed(self._a)))returnstr(list(iter(self)))

defmain():
    stack = Stack()
    stack.push('a')
    stack.push('b')
    stack.push('c')
    stack.pop()
    print(stack)
    if stack:
        print("stack not empty")
    stack.pop()
    stack.pop()
    if stack.isEmpty():
        print("stack empty")

if __name__ == '__main__':
    main()

Post a Comment for "Implementing Stack With Python"