Stack Implementation in Python

In this class, we do Stack Implementation in Python.

For Complete YouTube Video: Click Here

Stack

This stack implementation in python will help to the reader a lot in solving the data structure placement questions.

The reader should implement all the data structures in python. With the help of this stack implementation.

If you are not good at data structures. please check our data structures course.

The concepts of data structures are very important in improving the coding skill.

Let’s refresh the concept of stack. then we go for implementation.

Stack is a data structure that follows Last in First out order.

The element that is inserted last should be removed first.

In order to maintain the stack we need a variable to point the top of the stack.

The variable that point to top of the stack we call stack top.

Initially, The variable stack top will point to -1.

The stack top pointing to -1 means stack is empty.

If variable stack top is pointing to the last position in the stack. we say stack is full.

The display operation on stack. we have to display elements in the stack from top to bottom.

Analyze the logic of the stack program given below. for better practice.

Program

import numpy as np

class stackdatastructure:
    def __init__(self,size):
        self.stack=np.ndarray((size,),dtype="i")
        self.stacktop=-1
    def push(self,element):
        if self.stacktop==len(self.stack):
            print("stack is full")
        else:
            self.stacktop+=1
            self.stack[self.stacktop]=element
            print("element inserted")
    def pop(self):
        if self.stacktop==-1:
            print("stack is empty")
        else:
            print("element pop is")
            print(self.stack[self.stacktop])
            self.stacktop-=1
    def display(self):
        print("elements in the stack are")
        for i in range(self.stacktop,-1,-1):
            print(self.stack[i])
ob1=stackdatastructure(5)
ob1.push(10)
ob1.push(20)
ob1.display()
ob1.pop()
ob1.display()

in the above program, we defined a stack class.

For implementing the stack one should have basics on class and object concept in python. Click here.

Operations on the stack are push, pop, and display.

Each operation functionality is defined in a method.

When we define a object to the above class, we send the size of the stack.

With this intuition we can easily solve the placement questions.

In the placement questions they will mention stack class is available. This means we can use the methods available in the stack.