Stack Project
import pickle
import os
# File to save the stack
STACK_FILE = "stack_data.pkl"
# Initialize the stack
stack = []
def push(item):
[Link](item)
print(f"'{item}' pushed to the stack.")
def pop():
if stack:
item = [Link]()
print(f"'{item}' popped from the stack.")
else:
print("Stack is empty. Nothing to pop.")
def peek():
if stack:
print(f"Top element is: '{stack[-1]}'")
else:
print("Stack is empty.")
def display():
if stack:
print("Stack contents:", stack)
else:
print("Stack is empty.")
def save_stack():
with open(STACK_FILE, "wb") as file:
[Link](stack, file)
print(f"Stack saved to '{STACK_FILE}'.")
def load_stack():
global stack
if [Link](STACK_FILE):
with open(STACK_FILE, "rb") as file:
stack = [Link](file)
print(f"Stack loaded from '{STACK_FILE}'.")
else:
print(f"No saved stack found at '{STACK_FILE}'.")
def main():
while True:
print("\n--- Stack Operations ---")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Save Stack")
print("6. Load Stack")
print("7. Exit")
choice = input("Enter your choice: ")
if choice == "1":
item = input("Enter item to push: ")
push(item)
elif choice == "2":
pop()
elif choice == "3":
peek()
elif choice == "4":
display()
elif choice == "5":
save_stack()
elif choice == "6":
load_stack()
elif choice == "7":
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Output-
Enter your choice: 1
Enter item to push: 10
'10' pushed to the stack.
Enter your choice: 1
Enter item to push: 20
'20' pushed to the stack.
Enter your choice: 1
Enter item to push: 30
'30' pushed to the stack.
Enter your choice: 4
Stack contents: ['10', '20', '30']
Enter your choice: 2
'30' popped from the stack.
Enter your choice: 4
Stack contents: ['10', '20']
Enter your choice: 5
Stack saved to 'stack_data.pkl'.
Enter your choice: 6
Stack loaded from 'stack_data.pkl'.
Enter your choice: 4
Stack contents: ['10', '20']
Enter your choice: 7
Exiting program. Goodbye!