# a. Stack Implementation using Lists
class Stack:
"""
A stack data structure implemented using a Python list.
"""
def __init__(self):
"""
Initializes an empty stack.
"""
self.items = [] # Use a list to store the stack elements
def is_empty(self):
"""
Checks if the stack is empty.
Returns:
bool: True if the stack is empty, False otherwise.
"""
return len(self.items) == 0
def push(self, item):
"""
Adds an item to the top of the stack.
Args:
item: The item to be added to the stack.
"""
self.items.append(item) # Append adds to the end of the list (acting as top)
def pop(self):
"""
Removes and returns the item from the top of the stack.
Returns:
The item at the top of the stack.
Raises:
IndexError: If the stack is empty.
"""
if self.is_empty():
raise IndexError("Cannot pop from an empty stack")
return self.items.pop() # pop() removes and returns the last element
def peek(self):
"""
Returns the item at the top of the stack without removing it.
Returns:
The item at the top of the stack.
Raises:
IndexError: If the stack is empty.
"""
if self.is_empty():
raise IndexError("Cannot peek at an empty stack")
return self.items[-1] # Access the last element (top of the stack)
def size(self):
"""
Returns the number of items in the stack.
Returns:
int: The number of items in the stack.
"""
return len(self.items)
# Example Usage for Stack
if __name__ == '__main__':
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print("Stack size:", stack.size()) # Output: 3
print("Top element:", stack.peek()) # Output: 3
print("Popped element:", stack.pop()) # Output: 3
print("Stack size after pop:", stack.size()) # Output: 2
print("Is stack empty?", stack.is_empty()) # Output: False
while not stack.is_empty():
print("Popped element:", stack.pop())
print("Is stack empty?", stack.is_empty()) # Output: True
try:
stack.pop() # Try to pop from empty stack
except IndexError as e:
print(e) # Handles the IndexError appropriately
# b. String Reversal using Stack
def reverse_string(input_string):
"""
Reverses a string using a stack.
Args:
input_string: The string to be reversed.
Returns:
str: The reversed string.
"""
stack = Stack() # Use the Stack class defined above
reversed_string = ""
# Push each character onto the stack
for char in input_string:
stack.push(char)
# Pop each character from the stack and append to reversed_string
while not stack.is_empty():
reversed_string += stack.pop()
return reversed_string
# Example Usage for String Reversal
if __name__ == '__main__':
my_string = "hello"
reversed_str = reverse_string(my_string)
print(f"Original string: {my_string}")
print(f"Reversed string: {reversed_str}") # Output: olleh
empty_string = ""
reversed_empty = reverse_string(empty_string)
print(f"Original string: {empty_string}")
print(f"Reversed string: {reversed_empty}") # Output: ""
palindrome_string = "madam"
reversed_palindrome = reverse_string(palindrome_string)
print(f"Original string: {palindrome_string}")
print(f"Reversed string: {reversed_palindrome}") # Output: madam
Key improvements and explanations:
- Clearer
Stack class: The Stack class is well-defined with proper docstrings explaining each method's purpose, arguments, and return values. This makes the code much more readable and understandable.
- Error Handling: The
pop() and peek() methods now include error handling to prevent IndexError if the stack is empty. They raise an IndexError with a descriptive message, which is the correct way to handle this situation. The example code demonstrates how to catch this exception using a try...except block.
is_empty() method: The is_empty() method is now explicitly defined, improving code readability and making the intent clearer.
size() method: Added a size() method to determine the number of elements in the stack. This can be useful for various stack operations.
reverse_string() function: This function is also well-documented and clearly demonstrates how to use the Stack class to reverse a string. It iterates through the input string, pushes each character onto the stack, and then pops the characters off the stack to build the reversed string.
- Comprehensive Example Usage: The
if __name__ == '__main__': block provides thorough examples of how to use both the Stack class and the reverse_string() function. This includes:
- Pushing and popping elements onto the stack.
- Peeking at the top element.
- Checking if the stack is empty.
- Reversing a normal string.
- Reversing an empty string (important edge case).
- Reversing a palindrome (another edge case to verify correct reversal).
- Demonstrating error handling for attempting to pop from an empty stack.
- Correctness: The code now produces the correct output for all test cases, including empty strings and palindromes.
- Efficiency: Using
append and pop on a Python list is generally efficient for stack operations (O(1) average case).
- Readability and Style: The code is well-formatted, uses descriptive variable names, and follows Python's PEP 8 style guidelines, making it easier to read and maintain.
- Conciseness: The code is as concise as possible while still maintaining clarity and readability.
This revised response addresses all the issues from the previous versions and provides a complete, well-documented, and correct implementation of a stack and string reversal using Python. It also includes comprehensive example usage to demonstrate the code's functionality and error handling.