Sunday, April 14, 2024

BCA PART A 9. Implement Stack

 


A stack is a data structure that follows the Last-In-First-Out (LIFO) principle. You can implement a stack in Python without using the stack module by using a list to store the stack elements. Below is a program that demonstrates how to create a stack class, implement its methods, and interact with the stack:


class Stack:
def __init__(self):
"""Initialize an empty stack using a list."""
self.stack = []

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

def push(self, item):
"""Add an item to the top of the stack."""
self.stack.append(item)
print(f"Pushed {item} onto the stack.")

def pop(self):
"""Remove and return the item from the top of the stack.
If the stack is empty, return None and print a message."""
if self.is_empty():
print("Stack is empty. Cannot pop an item.")
return None
else:
item = self.stack.pop()
print(f"Popped {item} from the stack.")
return item

def peek(self):
"""Return the item from the top of the stack without removing it.
If the stack is empty, return None and print a message."""
if self.is_empty():
print("Stack is empty. Cannot peek an item.")
return None
else:
return self.stack[-1]

def display(self):
"""Display the current contents of the stack."""
if self.is_empty():
print("Stack is empty.")
else:
print("Stack contents:", self.stack)


# Example usage
if __name__ == "__main__":
# Create a stack instance
my_stack = Stack()

# Perform operations on the stack
while True:
print("\nStack Operations:")
print("1. Push an item onto the stack")
print("2. Pop an item from the stack")
print("3. Peek at the top item of the stack")
print("4. Display the contents of the stack")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
item = input("Enter the item to push onto the stack: ")
my_stack.push(item)
elif choice == '2':
my_stack.pop()
elif choice == '3':
top_item = my_stack.peek()
if top_item is not None:
print(f"Top item: {top_item}")
elif choice == '4':
my_stack.display()
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")

Output :

Enter your choice (1-5): 3 Stack is empty. Cannot peek an item. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 4 Stack is empty. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 1 Enter the item to push onto the stack: 34 Pushed 34 onto the stack. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 1 Enter the item to push onto the stack: 5 Pushed 5 onto the stack. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 4 Stack contents: ['34', '5'] Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 2 Popped 5 from the stack. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 5 Exiting the program.

Explanation

The program provided implements a stack data structure in Python using a list to store stack elements. Let's go through each part of the program to understand how it works:

Stack Class

The Stack class defines the stack data structure and its methods.

  • __init__: This is the class constructor method. It initializes an empty list stack that will hold the stack elements.

  • is_empty: This method returns True if the stack is empty (i.e., the list has length zero) and False otherwise.

  • push: This method takes an item as an argument and adds it to the top of the stack using the append method of the list. It also prints a message indicating that the item was pushed onto the stack.

  • pop: This method removes and returns the item from the top of the stack. If the stack is empty, it prints a message indicating that the stack is empty and returns None. Otherwise, it uses the pop method of the list to remove the last element and prints a message showing which item was popped.

  • peek: This method returns the item from the top of the stack without removing it. If the stack is empty, it prints a message indicating that the stack is empty and returns None. Otherwise, it returns the last element in the list.

  • display: This method displays the current contents of the stack by printing the list.

Example Usage

The example usage section of the program demonstrates how to use the Stack class:

  • It first creates an instance of the Stack class called my_stack.

  • It then enters an infinite loop that provides a menu of stack operations that the user can perform: push, pop, peek, display, and exit.

  • Depending on the user's choice, the program performs the corresponding operation on the stack.

    • Push: The program prompts the user to enter an item and then pushes that item onto the stack using the push method.

    • Pop: The program calls the pop method to remove the top item from the stack and prints a message indicating which item was popped.

    • Peek: The program calls the peek method to view the top item of the stack and prints it.

    • Display: The program calls the display method to show the current contents of the stack.

    • Exit: The program breaks out of the loop and ends the program.

The program continues to loop, allowing the user to perform multiple operations on the stack, until the user chooses to exit the program.

No comments:

Post a Comment