Implement working of Stacks. (pop method to take the last item added off the stack and a push method to add an item to the stack)

in this tutorial we learn about stacks and python program Implement working of Stacks. (pop method to take the last item added off the stack and a push method to add an item to the stack) 
basically stack is a linear data structure , which follow a particular order in which the operation are perform 
basically the order is last in first out (lifo) or first in last out (filo) 
their are many real life example like plates in this example plates are stack over one another , the plate which is at the top of the stack that plat are push last on the stack but as order that first plat has bin pop first . but the first inserted plate is take longer time to pop because that plate is at the end on the stack 

this is real life example are clearly explain stack order last in first out (lifo) or first in last out(filo)

in the stack two method push or pop 
syntax of push method 

def push(self,value):


syntax of pop method

def pop(self):


code

class Stack:
    def __init__(self):
        self.items=[]
        self.size=0
    def push(self,value):
        self.items.append(value)
        self.size+=1
    def pop(self):
        if self.isEmpty():
            print("Stack is Empty")
        else:
            print("The popped number from the stack is",self.items.pop())
            self.size-=1
    def isEmpty(self):
        if(self.size==0):
            return True
        else:
            return False
    def display(self):
        print("starting from the top the stacck elements are positioned as:")
        self.i=self.size-1
        while self.i>=0:
            print(self.items[self.i])
            self.i-=1
    def peek(self):
        if self.isEmpty():
            print("Stack is Empty")
        else:
            print("The topmost element in the Stack is",self.items[self.size-1])
    def length(self):
        if self.isEmpty():
            print("Stack is Empty")
        else:
            print("The number of items in stack are:",self.size)
S=Stack()
print("Menu:")
print("1.Push \n2.Pop \n3.Peek \n4.Display \n5.Length \n6.Exit")
choice=int(input("Press your choice"))
while choice<=5:
    if(choice==1):
        value=int(input("Enter the number to be inserted in the stack"))
        S.push(value)
    elif(choice==2):
        S.pop()
    elif(choice==3):
        S.peek()
    elif(choice==4):
        S.display()
    elif(choice==5):
        S.length
    choice=int(input("Press your choice"))    

output
Implement working of Stacks. (pop method to take the last item added off the stack and a push method to add an item to the stack)



Post a Comment

0 Comments