13.2. Stacks & Queues#

Stacks and queues are linear abstract data types: their items sit in a single sequence, one after another. Both keep items in order, but they remove them in different orders.

Outline

Stacks
  o Last-in, first-out behavior
  o Python list implementation
  o Balanced brackets example
Queues
  o First-in, first-out behavior
  o Why deque, not list
  o collections.deque implementation
Stack or Queue?

13.2.1. Stacks#

A stack is a last-in, first-out (LIFO) structure: the newest item you add is the first one you remove.

Common stack operations:

  • push(item): add an item to the top

  • pop(): remove and return the top item

  • peek(): look at the top item without removing it

  • is_empty(): check whether the stack has no items

Stacks are useful for undo history, browser back buttons, expression evaluation, recursion, and depth-first traversal.

class Stack:
    def __init__(self):
        self._items = []

    def push(self, item):
        self._items.append(item)

    def pop(self):
        if self.is_empty():
            raise IndexError("pop from empty stack")
        return self._items.pop()

    def peek(self):
        if self.is_empty():
            raise IndexError("peek from empty stack")
        return self._items[-1]

    def is_empty(self):
        return len(self._items) == 0


history = Stack()
history.push("open file")
history.push("edit line 10")
history.push("rename variable")

print(history.pop())
print(history.pop())
rename variable
edit line 10

Stacks are also used to check whether brackets are balanced. Each open bracket is pushed. Each close bracket pops the stack and checks that the popped bracket is its partner. Other characters are skipped. At the end, the stack must be empty: an open bracket still on the stack, as in "((a + b)", was never closed.

def is_balanced(expression):
    stack = Stack()
    pairs = {')': '(', ']': '[', '}': '{'}

    for char in expression:
        if char in '([{':
            stack.push(char)
        elif char in ')]}':
            if stack.is_empty() or stack.pop() != pairs[char]:
                return False

    return stack.is_empty()


print(is_balanced("(a + b) * [c - d]"))   # True
print(is_balanced("(a + b] * [c - d]"))   # False
print(is_balanced("((a + b)"))            # False
True
False
False
### Exercise: Reverse Words with a Stack
# Write a function named reverse_words(sentence) that uses a Stack
# to reverse the order of words in a sentence.
#
# Example: reverse_words("data structures matter") should return
# "matter structures data".
# Call reverse_words("data structures matter") and print the result.
# Print exactly:
# matter structures data
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def reverse_words(sentence):
    stack = Stack()
    for word in sentence.split():
        stack.push(word)

    reversed_words = []
    while not stack.is_empty():
        reversed_words.append(stack.pop())

    return " ".join(reversed_words)


print(reverse_words("data structures matter"))
matter structures data

13.2.2. Queues#

A queue is a first-in, first-out (FIFO) structure: the item you added earliest is the first one you remove.

Common queue operations:

  • enqueue(item): add an item to the back

  • dequeue(): remove and return the front item

  • is_empty(): check whether the queue has no items

A Python list can act as a queue, but removing from its front is slow. lst.pop(0) shifts every remaining item one place to the left, so it costs O(n). A collections.deque (the double-ended queue from 13.1) is built so that both ends change in O(1) time: append() adds at the back and popleft() removes from the front. Use a deque whenever your code removes items from the front.

from collections import deque

waiting_list = ["alice", "bob", "charlie"]
waiting_deque = deque(["alice", "bob", "charlie"])

print(waiting_list.pop(0))       # alice, after shifting bob and charlie left: O(n)
print(waiting_deque.popleft())   # alice, with no shifting: O(1)
print(waiting_list, list(waiting_deque))
alice
alice
['bob', 'charlie'] ['bob', 'charlie']
from collections import deque


class Queue:
    def __init__(self):
        self._items = deque()

    def enqueue(self, item):
        self._items.append(item)

    def dequeue(self):
        if self.is_empty():
            raise IndexError("dequeue from empty queue")
        return self._items.popleft()

    def is_empty(self):
        return len(self._items) == 0


line = Queue()
line.enqueue("alice")
line.enqueue("bob")
line.enqueue("charlie")

print(line.dequeue())
print(line.dequeue())
alice
bob
### Exercise: Serve a Customer Line
# Create a Queue named customers.
# 1. Enqueue apple, then banana.
# 2. Serve one customer: call dequeue and print the result.
# 3. Enqueue cherry.
# 4. Serve two more customers, printing each result.
# Print exactly:
# apple
# banana
# cherry
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
customers = Queue()
customers.enqueue("apple")
customers.enqueue("banana")
print(customers.dequeue())

customers.enqueue("cherry")
print(customers.dequeue())
print(customers.dequeue())
apple
banana
cherry

13.2.3. Stack or Queue?#

Problem

Better structure

Reason

Undo edits

Stack

Undo the newest action first

Print jobs

Queue

Print the oldest waiting job first

Browser back button

Stack

Return to the most recent page

Help desk tickets

Queue

Serve earlier requests first

Depth-first search

Stack

Explore one path deeply before backing up

Breadth-first search

Queue

Explore nearby nodes first

### Exercise: Pick the Structure
# For each workflow, write "stack" or "queue" in the dictionary value.
# 1. Check that every opening HTML tag, such as <b>, has a matching closing tag
# 2. Process sensor readings in the order they arrive
# 3. Take coffee orders at a counter
# Print exactly:
# {'matching HTML tags': 'stack', 'sensor readings': 'queue', 'coffee orders': 'queue'}
### Your code starts here.

choices = {
    "matching HTML tags": "",
    "sensor readings": "",
    "coffee orders": "",
}

print(choices)

### Your code ends here.
{'matching HTML tags': '', 'sensor readings': '', 'coffee orders': ''}

Hide code cell source

### Solution
choices = {
    "matching HTML tags": "stack",   # like balanced brackets: close the newest open tag first
    "sensor readings": "queue",      # oldest reading first
    "coffee orders": "queue",        # first customer served first
}

print(choices)
{'matching HTML tags': 'stack', 'sensor readings': 'queue', 'coffee orders': 'queue'}