0% found this document useful (0 votes)
3 views4 pages

Stack Operations in Python Code

The document outlines a stack operation implementation using a list in Python, including functions for pushing, popping, peeking, and displaying stack elements. It provides a user interface for interacting with the stack through a menu-driven approach. The code also includes error handling for underflow conditions when attempting to pop or peek from an empty stack.

Uploaded by

mahigopan2022
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Stack Operations in Python Code

The document outlines a stack operation implementation using a list in Python, including functions for pushing, popping, peeking, and displaying stack elements. It provides a user interface for interacting with the stack through a menu-driven approach. The code also includes error handling for underflow conditions when attempting to pop or peek from an empty stack.

Uploaded by

mahigopan2022
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STACK OPERATION

AIM:
To Push and Pop a value from a Stack using list.

CODING:
def isEmpty(stk):
if stk == []:
return True
else:
return False

def Push(stk, item):


[Link](item)
top = len(stk) - 1

def Pop(stk):
if isEmpty(stk):
return ('Under ow')
else:
item = [Link]()
if len(stk) == 0:
top = None
else:
top = len(stk) - 1
return item

def Peek(stk):
if isEmpty(stk):
return ('Under ow')
fl
fl
else:
top = len(stk) - 1
return stk[top]

def Display(stk):
if isEmpty(stk):
print('Stack is Empty')
else:
t = len(stk) - 1
print(stk[t], ':Top')
t=t-1
while (t >= 0):
print(stk[t])
t -= 1

s = []
print('1. Push')
print('2. Pop')
print('3. Peek')
print('4. Display')
print('5. Exit')

while True:
ch = int(input('Enter your choice(1-5) '))
if ch == 1:
val = int(input('Enter item to Push : '))
Push(s, val)
elif ch == 2:
val = Pop(s)
if val == 'Under ow':
print('Stack Empty')
fl
else:
print('Top item : ', val)
elif ch == 3:
item = Peek(s)
if item == 'Under ow':
print('Stack Empty')
else:
print('Top item : ', item)
elif ch == 4:
Display(s)
elif ch == 5:
break
fl
OUTPUT:

You might also like