0% found this document useful (0 votes)
6 views6 pages

Final CS Main

Final cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views6 pages

Final CS Main

Final cs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

AIM :

Write a program to implement a Stack for these


book details (book number, book name). Each
node of the Stack contains two types of
information - a book number and its name.
Implement PUSH and display operations.
Documentation :

 Source

File: 5.22

exp-8

 File Size:

7.00 KB

 Python Version:

Python 3.11.4

 Module Used:

IDLE

 Functions Used:

1)push() - Used to add a book to the stack.

2)pop() - Used to remove the top book from the stack.


3)display() - Used to display the current stack of books.

4)init () - Used in class-based

implementations for initialization.

Al
go
rit
h
m:
1. Initialize the Stack:
- Create an empty stack (using a list or linked list).

- Eachnode will contain book_no (book number) and


book_name (book name).

2. Define the push() function:


- Add a new book (with book_no and book_name) to the
top of the stack.

3. Define the pop() function:


- Remove and return the top book from the stack.

- If the stack is empty, display an error message.


4. Define the display() function:
- Show all books in the stack from top to bottom.

- If the stack is empty, display a message indicating that.


5. Edge Case Handling:
- Handle empty stack conditions in both the pop() and
display() functions.

Code
def is_empty(stk):
"""Check if the stack is empty."""
return len(stk) == 0

def push(stk, item):


"""Push an item onto the stack."""
stk.append(item)

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:

You might also like