Tuesday, 6 August 2019

Prog-9 Write a Python program to implement a stack using a list data-structure.


class Stack:
    def __init__(self):
        self.items = []
    def is_empty(self):
        return self.items == []
    def push(self, data):
        self.items.append(data)
    def pop(self):
        return self.items.pop()
 
s = Stack()
while True:
    print('Press 1 for push')
    print('Press 2 for pop')
    print('Press 3 for quit')
    do = int(input('What would you like to do'))
    if do == 1:
        n=int(input("enter a number to push"))
        s.push(n)
    elif do == 2:
        if s.is_empty():
            print('Stack is empty.')
        else:
            print('Popped value: ', s.pop())
    elif do == 3:
        break


Output:

What would you like to do 1
enter a number to push 5
Press 1 for push
Press 2 for pop
Press 3 for quit
What would you like to do 1
enter a number to push 3
Press 1 for push
Press 2 for pop
Press 3 for quit
What would you like to do 1
enter a number to push 6
Press 1 for push
Press 2 for pop
Press 3 for quit
What would you like to do 2
Popped value:  6
Press 1 for push
Press 2 for pop
Press 3 for quit
What would you like to do 2
Popped value:  3
Press 1 for push
Press 2 for pop
Press 3 for quit
What would you like to do 2
Popped value:  5
Press 1 for push
Press 2 for pop
Press 3 for quit
What would you like to do 2
Stack is empty.
Press 1 for push
Press 2 for pop
Press 3 for quit
What would you like to do 2
Stack is empty.
Press 1 for push
Press 2 for pop
Press 3 for quit
What would you like to do 3
>>> 

No comments:

Post a Comment