3/40
Part 2 of 8 · The heapLearn and do
Only heap[0] has a known place, and the rest of the list isn't sorted
heapify turns a list into a heap, but it doesn't sort it. Watch what it does to seven numbers.
import heapq
h = [30, 12, 45, 7, 21, 18, 60]
heapq.heapify(h)
print(h)
print(h[:4])
print(heapq.nsmallest(4, h))
[7, 12, 18, 30, 21, 45, 60]
[7, 12, 18, 30]
[7, 12, 18, 21]
h[0] is the smallest. The rest isn't sorted: 30 sits before 21. So h[:4] is not the four smallest, and heapq.nsmallest is.
A heap keeps exactly one item in a known place. The second smallest is at index 1 or 2. Nothing past that is promised.
In the editor, h is the heap that heapify made. Write first_k(h, k): its k smallest items, smallest first, and leave h as it was.