Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 66 / 101

Next most important, please.

Schedule by priority without sorting the whole backlog after every insertion.

ADVANCED LAB
BY NAVAN SAMI◷ 9 MIN READPYTHON 3

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.

heaps.py
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)
↳ EXPECTED OUTPUT
1 Fix
1 Test
3 Polish

03 Under the hood

  1. 1

    The smallest numeric priority is processed first. State that convention so callers do not assume larger numbers mean more urgency.

  2. 2

    The increasing order value breaks ties consistently and prevents Python from needing to compare arbitrary task objects.

  3. 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

A SMALL MISSION

Find the three smallest values without sorting the complete input explicitly.

Reveal one possible solution +
one_possible_solution.py
import heapq
print(heapq.nsmallest(3, [9, 1, 7, 2, 8, 3]))

05 Check your signal

QUICK SIGNAL CHECK

Is the heap’s entire backing list sorted?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.