Saturday, August 31, 2024

Stack in Python

Follow me

Stack using Python


Stack


Stack in Python

A Stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Stacks are widely used in applications like function call management, undo mechanisms in text editors, expression evaluation, and more.

Basic Stack Operations

  1. Push: Adds an element to the top of the stack.
  2. Pop: Removes and returns the top element from the stack.
  3. Peek: Returns the top element without removing it.
  4. isEmpty: Checks whether the stack is empty.
  5. Size: Returns the number of elements in the stack.

Implementing Stack in Python

1. Using a List

Python's built-in list can be used to implement a stack. Lists have methods like append() to add an element to the end (top of the stack) and pop() to remove the last element.

python

class Stack: def __init__(self): self.stack = [] def push(self, item): """Pushes an item onto the stack.""" self.stack.append(item) print(f"Pushed: {item}") def pop(self): """Removes the top item from the stack and returns it.""" if not self.is_empty(): popped_item = self.stack.pop() print(f"Popped: {popped_item}") return popped_item else: print("Stack is empty!") return None def peek(self): """Returns the top item of the stack without removing it.""" if not self.is_empty(): print(f"Top element: {self.stack[-1]}") return self.stack[-1] else: print("Stack is empty!") return None def is_empty(self): """Checks if the stack is empty.""" return len(self.stack) == 0 def size(self): """Returns the size of the stack.""" return len(self.stack) # Example Usage stack = Stack() stack.push(5) # Pushed: 5 stack.push(10) # Pushed: 10 stack.peek() # Top element: 10 stack.pop() # Popped: 10 stack.is_empty() # False stack.pop() # Popped: 5 stack.is_empty() # True

2. Using collections.deque

The deque (double-ended queue) from Python's collections module is a more efficient choice for stack operations. It provides O(1) time complexity for append (push) and pop operations.

python

from collections import deque class Stack: def __init__(self): self.stack = deque() def push(self, item): """Pushes an item onto the stack.""" self.stack.append(item) print(f"Pushed: {item}") def pop(self): """Removes the top item from the stack and returns it.""" if not self.is_empty(): popped_item = self.stack.pop() print(f"Popped: {popped_item}") return popped_item else: print("Stack is empty!") return None def peek(self): """Returns the top item of the stack without removing it.""" if not self.is_empty(): print(f"Top element: {self.stack[-1]}") return self.stack[-1] else: print("Stack is empty!") return None def is_empty(self): """Checks if the stack is empty.""" return len(self.stack) == 0 def size(self): """Returns the size of the stack.""" return len(self.stack) # Example Usage stack = Stack() stack.push(100) # Pushed: 100 stack.push(200) # Pushed: 200 stack.peek() # Top element: 200 stack.pop() # Popped: 200 stack.is_empty() # False stack.pop() # Popped: 100 stack.is_empty() # True

Deletion of Stack in Python

Deleting a stack generally means removing all its elements, making it empty. In the context of a stack, deletion can refer to:

  1. Removing the Top Element: The pop() operation removes the top element of the stack.
  2. Clearing the Entire Stack: This operation removes all elements, effectively deleting the stack.

1. Removing the Top Element (pop)

The pop() method removes the element that was most recently added to the stack. Here's how you can use the pop() method:

python

def pop(self): if not self.is_empty(): removed_item = self.stack.pop() print(f"Popped {removed_item} from stack.") return removed_item else: print("Stack is empty, cannot pop.")

2. Clearing the Entire Stack

To delete all the elements from the stack, we can define a clear() method that empties the stack using the clear() method of the Python list:

python

def clear(self): self.stack.clear() print("Stack cleared.")

Updated Implementation with Deletion

Here’s an updated version of the Stack class with a clear() method:

python

class Stack: def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) print(f"Pushed {item} to stack.") def pop(self): if not self.is_empty(): removed_item = self.stack.pop() print(f"Popped {removed_item} from stack.") return removed_item else: print("Stack is empty, cannot pop.") def peek(self): if not self.is_empty(): print(f"Top item is {self.stack[-1]}.") return self.stack[-1] else: print("Stack is empty, nothing to peek.") def is_empty(self): return len(self.stack) == 0 def size(self): return len(self.stack) def display(self): print("Stack elements are:", self.stack) def clear(self): self.stack.clear() print("Stack cleared.")

Example Usage for Deletion

python

# Create a Stack instance my_stack = Stack() # Push elements to the stack my_stack.push(10) my_stack.push(20) my_stack.push(30) # Display current stack my_stack.display() # Pop an element from the stack my_stack.pop() # Clear the entire stack my_stack.clear() # Display current stack my_stack.display()

Summary

  • Deleting the Top Element: Use the pop() method to remove the topmost item from the stack.
  • Clearing the Entire Stack: Use the clear() method to remove all items from the stack at once.
  • A Stack is a LIFO data structure where the last element added is the first one to be removed.
  • Key operations are push, pop, peek, isEmpty, and size.
  • Stacks can be implemented using Python’s list or collections.deque.
  • Lists are simple but can be slower for large stacks, while deque offers better performance for stack operations.

No comments:

Post a Comment

Online Calculator

Follow Me 0 C % / * 7 8 9 - 4 5 6 +...