STACK FOR BOOKS

Write a program to create a Stack by name BooksStack with the following detail like book_title, author_name, and publication_year.

  • Specified operation on the stack BooksStack. Like             

  • push_book(BooksStack, new_book)

  • pop_book(BooksStack)

  • peep(BookStack)

  • Display the full stack of book

Solution :- 

def push_book(BooksStack, new_book): BooksStack.append(new_book) print(f"Book '{new_book['book_title']}' added to the stack.") def pop_book(BooksStack): if not BooksStack: print("Stack is empty. No book to remove.") return None removed_book = BooksStack.pop() print(f"Book '{removed_book['book_title']}' removed from the stack.") return removed_book def peep(BooksStack): if not BooksStack: print("Stack is empty. No book to view.") return None top_book = BooksStack[-1] print(f"Top book is '{top_book['book_title']}' by {top_book['author_name']} ({top_book['publication_year']}).") return top_book def display_stack(BooksStack): if not BooksStack: print("Stack is empty.") return print("Books in the stack:") for i in range(len(BooksStack)-1,-1,-1): print(BooksStack[i]) BooksStack = [] while True: print("\nChoose an operation:") print("1. Push a book") print("2. Pop a book") print("3. Peep at the top book") print("4. Display all books") print("5. Exit") choice = input("Enter your choice (1-5): ") if choice == '1': book_title = input("Enter book title: ") author_name = input("Enter author name: ") publication_year = input("Enter publication year: ") new_book = { "book_title": book_title, "author_name": author_name, "publication_year": publication_year } push_book(BooksStack, new_book) elif choice == '2': pop_book(BooksStack) elif choice == '3': peep(BooksStack) elif choice == '4': display_stack(BooksStack) elif choice == '5': print("Exiting program. Goodbye!") break else: print("Invalid choice. Please select a valid option.")

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.