Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, November 23, 2020

Python program to perform the operation on stack in python by G Krishna Chauhan

Source Code


 class Stack:

    def __init__(self):

        self.items = [ ]

    def isEmpty(self): # Checks whether the stack is empty or not

        

        return self.items == [ ]

    def push(self, item): #Insert an element

        self.items.append(item)

        

    def pop(self): # Delete an element

        return self.items.pop( )

    

    def peek(self): #Check the value of top

        return self.items[len(self.items)-1]

    

    def size(self): # Size of the stack i.e. total no. of elements in stack

        return len(self.items)

    

s = Stack( )

print("MENU BASED STACK")

cd=True


while cd:

    print(" 1. Push ")

    print(" 2. Pop ")

    print(" 3. Display ")

    print(" 4. Size of Stack ")

    print(" 5. Value at Top ")


    choice=int(input("Enter your choice (1-5) : "))


    if choice==1:

        val=input("Enter the element: ")

        s.push(val)

        

    elif choice==2:

        if s.items==[ ]:

            print("Stack is empty")

        else:

            print("Deleted element is :", s.pop( ))

            

    elif choice==3:

        print(s.items)

        

    elif choice==4:

        print("Size of the stack is :", s.size( ))

        

    elif choice==5:

        print("Value of top element is :", s.peek( ))

        

    else:

        print("You enetered wrong choice ")

        

    print("Do you want to continue? Y/N")

    option=input( )

    if option=='y' or option=='Y':

        var=True

    else:

        var=False



OUTPUT


MENU BASED STACK
 1. Push 
 2. Pop 
 3. Display 
 4. Size of Stack 
 5. Value at Top 
Enter your choice (1-5) : 1
Enter the element: 9
Do you want to continue? Y/N
Y
 1. Push 
 2. Pop 
 3. Display 
 4. Size of Stack 
 5. Value at Top 
Enter your choice (1-5) : 1
Enter the element: 18
Do you want to continue? Y/N
Y
 1. Push 
 2. Pop 
 3. Display 
 4. Size of Stack 
 5. Value at Top 
Enter your choice (1-5) : 3
['9', '18']
Do you want to continue? Y/N
Y
 1. Push 
 2. Pop 
 3. Display 
 4. Size of Stack 
 5. Value at Top 
Enter your choice (1-5) : 4
Size of the stack is : 2
Do you want to continue? Y/N
Y
 1. Push 
 2. Pop 
 3. Display 
 4. Size of Stack 
 5. Value at Top 
Enter your choice (1-5) : 5
Value of top element is : 18
Do you want to continue? Y/N
Y
 1. Push 
 2. Pop 
 3. Display 
 4. Size of Stack 
 5. Value at Top 
Enter your choice (1-5) : 2
Deleted element is : 18
Do you want to continue? Y/N
Y
 1. Push 
 2. Pop 
 3. Display 
 4. Size of Stack 
 5. Value at Top 
Enter your choice (1-5) : 3
['9']
Do you want to continue? Y/N
Y
 1. Push 
 2. Pop 
 3. Display 
 4. Size of Stack 
 5. Value at Top 
Enter your choice (1-5) : 5
Value of top element is : 9

No comments:

Post a Comment