Next most important, please.
Schedule by priority without sorting the whole backlog after every insertion.
01 The idea
A min-heap keeps its smallest element at the root while maintaining a partial ordering among the rest. heapq operates on ordinary lists with push and pop operations that take logarithmic time. The underlying list is not completely sorted. For task scheduling, store tuples containing a priority and a deterministic tie-breaker.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
import heapq
queue = []
for order, (priority, name) in enumerate([(3, "Polish"), (1, "Fix"), (1, "Test")]):
heapq.heappush(queue, (priority, order, name))
while queue:
priority, _, name = heapq.heappop(queue)
print(priority, name)1 Fix 1 Test 3 Polish
03 Under the hood
- 1
The smallest numeric priority is processed first. State that convention so callers do not assume larger numbers mean more urgency.
- 2
The increasing order value breaks ties consistently and prevents Python from needing to compare arbitrary task objects.
- 3
heapify builds a heap from an existing list in linear time. Do not mutate an item’s priority in place without repairing the heap; insert a revised entry and manage stale entries or use a suitable abstraction.
04 Your turn, builder
Find the three smallest values without sorting the complete input explicitly.
Reveal one possible solution +
import heapq
print(heapq.nsmallest(3, [9, 1, 7, 2, 8, 3]))05 Check your signal
Is the heap’s entire backing list sorted?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.