Stack with python
Learn basic operations in stack with python. This program will help student to understand basic operations of stack. This is best for beginner to start with.
In this program we have covered following operations.
- Push
- Pop
- Seek
- Length
class Stack : # Creates an empty stack. def __init__( self ): self.items = list() self.size=0 #Author : ITVoyagers Website : itvoyagers.in # Returns True if the stack is empty or False otherwise. def isEmpty( self ): if(self.size==0): return True else: return False # Returns the number of items in the stack. def length ( self ): if self.isEmpty(): print("Stack is empty") else: print("number of items present is list are",self.size) #Author : ITVoyagers Website : itvoyagers.in # Returns the top item on the stack without removing it. def peek( self ): if self.isEmpty(): print("Stack is empty") else: print("top most element is", self.items[self.size-1]) #Author : ITVoyagers Website : itvoyagers.in # Removes and returns the top item on the stack. def pop( self ): if self.isEmpty(): print("Stack is empty") else: print("the poped elememt is ", self.items.pop()) self.size-=1 #Author : ITVoyagers Website : itvoyagers.in # Push an item onto the top of the stack. def push( self, item ): self.items.append(item) self.size+=1 s=Stack() print("Menu") print("1.push n2.pop n3.peek n4.length") #Author : ITVoyagers Website : itvoyagers.in ch=int(input("Enter your choice")) while ch<=4: if(ch==1): value=int(input("Enter value to be inserted")) s.push(value) elif (ch==2): s.pop() elif (ch==3): s.peek() elif (ch==4): s.length() ch=int(input("Enter your choice"))
Output :
Menu 1.push 2.pop 3.peek 4.length Enter your choice1 Enter value to be inserted50 Enter your choice1 Enter value to be inserted60 Enter your choice1 Enter value to be inserted70 Enter your choice2 the poped elememt is 70 Enter your choice3 top most element is 60 Enter your choice4 number of items present is list are 2 Enter your choice
Note : Please note that above program is compatible with Python 3 or higher version.