📚

Hands-on with Stacks and Queues in Python

Jul 17, 2024

Lecture: Hands-on with Stacks and Queues in Python

Overview

  • Focus: Hands-on demonstration of stacks and queues using Python.
  • Goal: Show how to use built-in Python data structures to implement stacks and queues.

Stacks

  • Data Structure Used: List
  • Key Operations:
    • Push: data.append(element)
    • Pop: element = data.pop()
  • Additional Operation:
    • Peek: element = data[len(data) - 1]
  • Behavior: LIFO (Last In First Out)
  • Example: data = [] data.append(5) element = data.pop() print(element) # Output: 5 print(data) # Output: []
  • Notes:
    • Limit to append and pop to maintain stack integrity.
    • Peek operation: element = data[len(data) - 1]
    • Visual example with multiple operations for better understanding.

Queues

  • Data Structure Used: List
  • Key Operations:
    • Enqueue: data.append(element)
    • Dequeue: element = data.pop(0)
  • Additional Operation:
    • Peek: element = data[0]
  • Behavior: FIFO (First In First Out)
  • Example: data = [] data.append(5) data.append(10) element = data.pop(0) print(element) # Output: 5 print(data) # Output: [10]
  • Notes:
    • Dequeue operation: element = data.pop(0)
    • Peek operation: element = data[0]
    • Consider performance impact for large lists (O(n) complexity).

Using deque from collections

  • Purpose: Optimize pop left operation.
  • Import: from collections import deque
  • Operations:
    • Append: data.append(element)
    • Pop Left: element = data.popleft()
  • Example: from collections import deque data = deque() data.append('Caleb') element = data.popleft() print(element) # Output: Caleb print(data) # Output: deque([])
  • Notes: Efficient for queue operations.

Custom Classes for Stacks and Queues

  • Purpose: Strict control over operations and extendibility.
  • Example - Custom Stack Class: class Stack: def __init__(self): self._data = [] def push(self, data): self._data.append(data) def pop(self): return self._data.pop() def peek(self): return self._data[len(self._data) - 1]
  • Usage: stack = Stack() stack.push(10) print(stack.peek()) # Output: 10 print(stack.pop()) # Output: 10
  • Notes:
    • Use underscores for private variables to discourage direct access.
    • Flexibility to add custom logic or enforce rules.
    • Extend for other data structures like queues or priority queues.

Takeaway

  • Adapt these concepts to other programming languages for practice.
  • Use built-in structures but also learn to implement custom classes for full control.

Next Steps: Continue to practice with hands-on examples and build a deeper understanding of data structures.