Advertisement
thespeedracer38

Stack in Python

Oct 19th, 2020
2,126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. def push(STACK,item):
  2.     STACK.append(item)
  3.  
  4. def is_empty(STACK):
  5.     if len(STACK)==0:
  6.         return True
  7.     else:
  8.         return False
  9.    
  10. def pop(STACK):
  11.     if is_empty(STACK)==True:
  12.         ret="STACK UNDERFLOW"
  13.         print("STACK UNDERFLOW")
  14.     else:
  15.         ret=STACK.pop()
  16.     return ret
  17.  
  18. def display(STACK):
  19.     if is_empty(STACK)==True:
  20.         print("STACK IS EMPTY")
  21.     else:
  22.         print("The elements of the stack are")
  23.         for i in range(len(STACK)-1,-1,-1):
  24.             print(STACK[i])
  25.  
  26. def peek(STACK):
  27.     if is_empty(STACK)==True:
  28.         ret="STACK UNDERFLOW"
  29.     else:
  30.         ret=STACK[len(STACK)-1]
  31.     return ret
  32.  
  33. # Stack is initially empty
  34. STACK = []
  35.  
  36. while True:
  37.     print("\nStack Options")
  38.     print("1. Push")
  39.     print("2. Pop")
  40.     print("3. Display Stack")
  41.     print("4. Peek")
  42.     print("5. Exit")
  43.     choice = int(input("Enter your choice (1-5): "))
  44.     if choice == 1:
  45.         item = int(input("Enter the item: "))
  46.         push(STACK, item)
  47.     elif choice == 2:
  48.         item = pop(STACK)
  49.         if item != "STACK UNDERFLOW":
  50.             print(item, "was deleted from the stack")
  51.         else:
  52.             print("STACK UNDERFLOW")
  53.     elif choice == 3:
  54.         display(STACK)
  55.     elif choice == 4:
  56.         item = peek(STACK)
  57.         print(item, "is present at the top of the stack")
  58.     elif choice == 5:
  59.         break
  60.     else:
  61.         print("Invalid choice")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement