Sorting and Ranking
Top-K Select
Find the three largest values in a list by repeated max-pick: locate the
current maximum, record it, remove it from the working copy, and repeat.
The replay shows work shrinking and result filling one element at a time.
By hand
The Pythonic way
heapq.nlargest(3, values) returns the three largest values in descending
order without modifying the input. Internally it maintains a min-heap of
size k, scanning the list once in O(n log k) — more efficient than repeated
max for large k.
naive.py
values = [4, 7, 2, 9, 5, 8, 1, 6]
work = list(values)
result = []
for _ in range(3):
best = max(work)
result.append(best)
work.remove(best)
print('RESULT:', result)
library.py
import heapq
values = [4, 7, 2, 9, 5, 8, 1, 6]
result = heapq.nlargest(3, values)
print('RESULT:', result)
RESULT: [9, 8, 7]
Implementation notes
work.remove(best)removes the first occurrence of the maximum; since all values here are distinct, this is unambiguous.- The loop variable
_signals "the count matters, the value does not"; it still appears in the trace as 0, 1, 2. - For k ≪ n, prefer
heapq.nlargest; for k close to n,sorted(values, reverse=True)[:k]is simpler; for k = 1, justmax(values).