Sub topic 8
Max-heaps, tuple priorities and tie-breaking
This chapter assumes you know Python lists and tuples, the heap property, and basic use of heapq from the previous chapter. Here you will learn three techniques that cover most real uses of heapq: getting a max-heap, attaching a payload to a priority, and keeping equal priorities in a predictable order.
Getting a max-heap from heapq
heapq only provides a min-heap. The smallest item is always at index 0. To get the largest item first, store the negated priority and negate it again when you read it back.
import heapq
max_heap = []
for x in [5, 1, 8, 3]:
heapq.heappush(max_heap, -x)
print(-heapq.heappop(max_heap)) # 8
print(-max_heap[0]) # 5, the next largest (peek)Negation works for numbers only. For other keys, such as strings, wrap the value in a small class that reverses the comparison, or sort by a numeric key derived from the value.
Attaching a payload with tuples
A heap of bare numbers is rarely useful. You usually need to know which task a priority belongs to. Python compares tuples element by element, left to right, so a tuple (priority, payload) is ordered by priority first.
import heapq
tasks = []
heapq.heappush(tasks, (2, "write report"))
heapq.heappush(tasks, (1, "fix outage"))
print(heapq.heappop(tasks)) # (1, 'fix outage')The tie-breaking problem
If two tuples have equal priorities, Python moves on and compares the payloads. That causes two problems:
- If the payloads cannot be compared, such as dictionaries or custom objects,
heappushraisesTypeError. - If they can be compared, equal priorities come out in payload order, not in the order you added them.
The usual fix is a unique counter between the priority and the payload. The counter is never equal for two entries, so Python never reaches the payload. Because the counter grows, it also gives first-in, first-out order among equal priorities.
import heapq
from itertools import count
tie = count()
tasks = []
heapq.heappush(tasks, (2, next(tie), "write report"))
heapq.heappush(tasks, (1, next(tie), "fix outage"))
heapq.heappush(tasks, (1, next(tie), "reply to email"))
while tasks:
priority, _, name = heapq.heappop(tasks)
print(priority, name)
# 1 fix outage
# 1 reply to email
# 2 write reportCombining a max-heap with tie-breaking
To pop the highest priority first and still keep insertion order among equals, negate only the priority. Keep the counter positive.
import heapq
from itertools import count
tie = count()
heap = []
for score, name in [(5, "a"), (9, "b"), (9, "c")]:
heapq.heappush(heap, (-score, next(tie), name))
score, _, name = heapq.heappop(heap)
print(-score, name) # 9 bIf you negated the counter as well, equal priorities would come out last-in, first-out. That is occasionally what you want, but it should be a deliberate choice.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Forgetting to negate when reading back | Wrong sign in output | Negate on push and on pop or peek |
| Omitting the counter | `TypeError` or unstable order | Add `(priority, next(tie), payload)` |
| Negating the counter in a max-heap | Equal priorities come out newest first | Negate only the priority |
| Mutating a priority inside the heap | Heap property silently breaks | Pop and push a new entry instead |
Exercise
You store (-priority, next(tie), job) in a heap and want to print the job with the highest priority. Which expression gives that job after entry = heapq.heappop(heap), and why does a job added earlier win a tie?
Show answer
Use entry[2]. The heap pops the smallest tuple, and the smallest negated priority is the largest real priority. Among equal priorities, the counter decides, and an earlier job has a smaller counter, so it compares as smaller and pops first.
Exercise
Why does heapq.heappush(h, (1, {"a": 1})) followed by heapq.heappush(h, (1, {"b": 2})) fail?
Show answer
The two priorities are equal, so Python compares the dictionaries, and dictionaries do not support <. This raises TypeError. A unique counter before the payload prevents the comparison.