Python 3D Academyবাংলা

heapq: always the smallest first

🌍 In real life. In a hospital emergency room, patients aren't seen in the order they arrive. A nurse gives each one a priority (1 = most urgent), and the doctor always takes the most urgent patient next. New patients keep arriving, so the list changes all the time.

Sorting the whole list after every arrival would work, but it's wasteful. A heap is a list kept in a clever, half-sorted order where the smallest item is always at index 0. Step by step:

  1. heapq.heappush(h, x) adds x and keeps the heap rule
  2. heapq.heappop(h) takes out the smallest and keeps the heap rule
  3. the rule: every parent is no bigger than its children, where the children of index i are at 2*i+1 and 2*i+2
  4. each push or pop only does a few swaps, even for a huge list

The idea in one sentence: a heap is a list arranged so the smallest item is always at index 0, and heapq.heappush/heappop add and remove items while keeping that true.

Its words:

  • priority queue: always serve the most urgent (smallest) item next
  • heapq.heappush(h, x) / heapq.heappop(h): add, and take the smallest
  • heapq.heapify(h): rearrange an existing list into a heap
  • (priority, name) tuples: the priority decides the order

Watch the heap work. The same list is drawn twice: as a tree on top (index 0 is the root) and as the real list underneath. Red means urgent (small), blue means it can wait (big). A pushed number joins at the end and climbs while it's smaller than its parent. A pop takes the top to the tray, moves the last item up, and lets it sink below any smaller child.

import heapq

h = [5, 3, 8, 1]
heapq.heapify(h)
print(h)
heapq.heappush(h, 2)
print(h, "smallest:", h[0])
print([heapq.heappop(h) for _ in range(len(h))])
heapify turns any list into a heap in place. The list isn't fully sorted ([1, 2, 8, 5, 3]); only h[0] is promised to be the smallest. Popping everything gives them all in order.

Patients, not just numbers. Push a tuple (priority, name). Tuples compare by their first item, so the priority decides; for a tie, the second item (the name) decides. Don't push dicts: Python can't tell whether one dict is "smaller" than another and stops with a TypeError.

For the biggest first (a max-heap), push the negative: -score. And when you only want the top few, heapq.nsmallest(k, items) and heapq.nlargest(k, items) do it in one call.

import heapq

er = []
heapq.heappush(er, (3, "sprained ankle"))
heapq.heappush(er, (1, "heart attack"))
heapq.heappush(er, (2, "broken arm"))
heapq.heappush(er, (1, "bad allergy"))

while er:
    priority, case = heapq.heappop(er)
    print(priority, case)

scores = [72, 95, 88, 60, 91]
print(heapq.nlargest(3, scores))
print(heapq.nsmallest(2, scores))
Two patients have priority 1, so the names break the tie: "bad allergy" comes before "heart attack" alphabetically.

Why a heap instead of sorting? Sorting the whole list every time a patient arrives costs about n × log n each time. A push or pop only climbs or sinks one path of the tree, about log₂ n steps: for 1,000,000 items, about 20. That's why heaps run priority queues, Dijkstra's shortest paths (World 8) and "the k smallest" problems.

Mistakes and edge cases.

  • Expecting a sorted list. After heapify([5, 1, 3]) the list is [1, 5, 3]: only index 0 is guaranteed to be the smallest.
  • heappop on a plain list. Popping from a list that was never heapified gives wrong answers, with no error. Call heapify first.
  • Items that can't be compared. Pushing dicts gives TypeError: '<' not supported between instances of 'dict' and 'dict'; push (priority, name) tuples.
  • Wanting the largest. heapq is a min-heap; push -priority to get the largest first.

Quiz

  1. What does this print?

    import heapq
    
    h = []
    for x in [5, 1, 4]:
        heapq.heappush(h, x)
    print(h[0])
  2. What does this print?

    import heapq
    
    h = [3, 1, 2]
    heapq.heapify(h)
    print(heapq.heappop(h), heapq.heappop(h))
  3. After some pushes, what is promised about the heap list h?

    • h[0] is the smallest item
    • The whole list is sorted
    • h[-1] is the biggest item
  4. What does this print?

    import heapq
    
    print(heapq.nlargest(2, [4, 9, 1, 7]))
  5. What does this print?

    import heapq
    
    er = []
    heapq.heappush(er, (2, "cut"))
    heapq.heappush(er, (1, "heart"))
    heapq.heappush(er, (3, "cold"))
    print(heapq.heappop(er)[1])
  6. This should print the smallest number, 1, but it prints 5. Which line is missing a step?

    import heapq
    nums = [5, 1, 3]
    print(heapq.heappop(nums))

Coding tasks

  1. Write triage(patients: list[tuple[int, str]]) -> list[str] with heapq: the names in the order they're seen, smallest priority first (and by name for a tie).

  2. Write cheapest(prices: dict[str, int], k: int) -> list[str]: the names of the k cheapest items, cheapest first, using heapq.nsmallest with key=prices.get.

  3. Finish the class Clinic. arrive(name, priority) adds a patient; next_patient() gives back the name of the most urgent one (smallest priority) and removes them, or None when nobody is waiting. Patients with the same priority are seen in the order they arrived, not by name.