Progress

Python Program for Stack using Array

Python Program for Stack using Array

Problem Statement: Write a program in Python to implement a Stack using an array.

Description: A Stack is an abstract data type or data structure which is based on LIFO (last in first out) policy. It means the element that we insert at last will be the first to be taken out.

Stack using array
Push and POP operation in Stack

We call Insert operation in Stack as Push and remove operation as Pop.

The Push and Pop operations have O(1) constant time complexity. Because a pointer is maintained at the top of the stack which manages Push and Pop operation.

Here is a complete tutorial and algorithm of Stack data structure.

Python Program: Stack Using Array

ArrayStack.py
Copy
class StackUsingArray:
    def __init__(self):
        self.stack = []

    #Method to append the element in the stack at top position.
    def push(self, element):
        self.stack.append(element)

    #Method to Pop last element from the top of the stack
    def pop(self):
        if(not self.isEmpty()):
            lastElement = self.stack[-1] #Save the last element to return
            del(self.stack[-1]) #Remove the last element
            return lastElement
        else:
            return("Stack Already Empty")

    #Method to check if stack is empty or not
    def isEmpty(self):
        return self.stack == []

    def printStack(self):
        print(self.stack)

#Driver code for pro players only :), BTY it is noob friendly.
if __name__ == "__main__":
    s = StackUsingArray()
    print("*"*5+" Stack Using Array HolyCoders.com "+5*"*")
    while(True):
        el = int(input("1 for Push\n2 for Pop\n3 to check if it is Empty\n4 to print Stack\n5 to exit\n"))
        if(el == 1):
            item = input("Enter Element to push in stack\n")
            s.push(item)
        if(el == 2):
            print(s.pop())
        if(el == 3):
            print(s.isEmpty())
        if(el == 4):
            s.printStack()
        if(el == 5):
            break

The program is based on the algorithm as described here.

Here is a quick explanation of the code.

  • The __init__() dunder method is the constructor and initializes an empty list (we use list instead of the array in Python).
  • Push method append a new data element on the top of the Stack.
  • Pop method removes the last element and returns it.
  • We need to check underflow condition in the Pop method, this is why we implement isEmpty method. The method isEmpty verify that the array is not empty before performing the Pop operation.

Note: We didn’t implement the check overflow method because Python lists have dynamic length (it keeps growing). In other programming language you need to implement it.

Here is a quick logic to check overflow condition.

check_overflow()
    return size(array_used_in_stack)== maximum

If Stack is full and we try to push a new data element it gives Stackoverflow error.

Share the Post ;)

Related Posts