Stacks In Python 5

stack implementation:2
(Using Functions)

To maintain elements using a stack

Operations:
Addition of elements (PUSH)
Deletion of elements (POP)
Traversal of elements (DISPLAY)

Creation of empty stack

s=[]

Push operation

a=input(“Enter any element “)
s.append(a)

Pop operation

if(s==[]):
    print(“Underflow / stack is empty”)
else:
    print(“poped element is “,s.pop())

To check stack is empty or not

if(s==[]):
    print(“stack is empty”)
else:
    print(“stack is not empty”)

Traversal operation

n=len(s)
for i in range(n-1,-1,-1):
    print(s[i])

Source Code

#stack implementation using functions
s=[]
def push():
        a=input("Enter any element to push ")
        s.append(a)
def pop():
        if(s==[]):
                print("Underflow / Stack in empty")
        else:
                print("poped element is ",s.pop())
def traverse():
        n=len(s)
        for i in range(n-1,-1,-1):
                print(s[i])
while True:
        print("1. Push");
        print("2. Pop");
        print("3. Traversal")
        print("4. Exit")
        ch=int(input("Enter your choice "))
        if(ch==1):
                push()
        elif(ch==2):
                pop();
        elif(ch==3):
                traverse()
        elif(ch==4):
                print("End")
                break
        else:
                print("Invalid choice")

Output:

1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 1
Enter any element to push Amit
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 1
Enter any element to push Sumit
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 1
Enter any element to push 100
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 3
100
Sumit
Amit
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 2
poped element is  100
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 3
Sumit
Amit
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 4
End
>>> 

Visitor Counter

0056701