Advertisement
Programmin-in-Python

Stack Implementation

Dec 22nd, 2020
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. def push(stack, item):
  2.     stack[0] = item
  3.  
  4. def pop(stack):
  5.     if bool(len(stack)):
  6.         print("Item popped : ", stack.pop(0))
  7.     else : print("[WARNING] Underflow!!!")
  8.  
  9. def peek(stack):
  10.     stk_len = len(stack)
  11.     if bool(stk_len):
  12.         for i in range(stk_len):
  13.             if i == 0:
  14.                 print(stack[i], " <== TOP\n")
  15.             else: print(stack[i], end="\n")
  16.     else: print("[WARNING] Stack is EMPTY!!!")
  17.  
  18. def main():
  19.     stack = []
  20.     print("The Stack is Empty now..\nPlease Enter 5 items into it...")
  21.     for i in range(5):
  22.         inp = input("Enter an Item : ")
  23.         stack.append(inp)
  24.     print("[SUCCESS] 5 Items Successfully added to it.")
  25.     print("\nPlease Enter the Operation that you want to do on it...")
  26.     while True:
  27.         print("\n1. Push\n2. Pop\n3. Peek\n4. Display Stack\n5. Exit")
  28.         choice = int(input("Enter the Choice (Number only) : "))
  29.         if choice == 1:
  30.             item = input("Enter the Item to be pushed : ")
  31.             push(stack, item)
  32.             print("[SUCCESS] Item Successfully Pushed into the stack.")
  33.         elif choice == 2 : pop(stack)
  34.         elif choice == 3 : peek(stack)
  35.         elif choice == 4 :
  36.             for i in stack : print(i)
  37.         elif choice == 5 :
  38.             print("Exiting...")
  39.             break
  40.         else : print("[ERROR] Invalid Choice")
  41. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement