Final CS Main
Final CS Main
Source
File: 5.22
exp-8
File Size:
7.00 KB
Python Version:
Python 3.11.4
Module Used:
IDLE
Functions Used:
Al
go
rit
h
m:
1. Initialize the Stack:
- Create an empty stack (using a list or linked list).
Code
def is_empty(stk):
"""Check if the stack is empty."""
return len(stk) == 0
def display(stk):
"""Display the items in the stack."""
if is_empty(stk):
print("Stack is empty")
else:
top = len(stk) - 1
print(stk[top], "is at the top")
for a in range(top - 1, -1, -1):
print(stk[a])
def main():
stack = []
while True:
print("\nSTACK OPERATIONS")
print("1. Push")
print("2. Display stack")
print("3. Exit")
try:
ch = int(input("Enter your choice (1-3): "))
except ValueError:
print("Invalid input! Please enter a number between 1 and
3.")
continue
if ch == 1:
try:
bno = int(input("Enter Book no. to be inserted: "))
bname = input("Enter Book name to be inserted: ")
item = [bno, bname]
push(stack, item)
input("Press Enter to continue...")
except ValueError:
print("Invalid input! Please enter a valid book number.")
elif ch == 2:
display(stack)
input("Press Enter to continue...")
elif ch == 3:
print("Exiting the program.")
break
else:
print("Invalid choice! Please select a valid option.")
input("Press Enter to continue...")
if __name__ == "__main__":
main()
Output: