Top-K Selection with a Bounded Heap
Select the k largest or smallest scores with heapq, keep memory bounded at k entries, and sort ties by name for stable output.
Code
import heapq
from collections.abc import Iterable
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Record:
score: float
name: str
def top_k(records: Iterable[Record], k: int, *, largest: bool = True) -> list[Record]:
if k < 0:
raise ValueError("k must be non-negative")
if k == 0:
return []
# nlargest/nsmallest keep only k candidates in an internal heap.
select = heapq.nlargest if largest else heapq.nsmallest
chosen = select(k, records, key=lambda record: record.score)
chosen.sort(
key=lambda record: (-record.score, record.name)
if largest
else (record.score, record.name),
)
return chosen
def main() -> None:
records = [
Record(92.5, "delta"),
Record(99.0, "alpha"),
Record(92.5, "charlie"),
Record(88.0, "bravo"),
Record(97.5, "echo"),
]
print([record.name for record in top_k(records, 3)])
print([record.name for record in top_k(records, 3, largest=False)])
if __name__ == "__main__":
main()
Inside the snippet
The working surface is the class Record and the functions top_k and main — everything else is wiring.
The import line is the dependency contract: Iterable, dataclass come from heapq and nothing else. The failure path is explicit — ValueError is raised when the guard condition holds.
Returns a newly built value, leaving the inputs as they were.
Caveats
- Plan for an install step:
heapqis a real dependency, resolved by the package manager. - The guard
k < 0short-circuits the flow with an earlyraisewhen its condition holds.
Putting it to use
The primary signature is def top_k(records: Iterable[Record], k: int, *, largest: bool = True) -> list[Record]
There are 1 call inside main — top_k — executed top to bottom.
Core lines
chosen.sort(
key=lambda record: (-record.score, record.name)
if largest
else (record.score, record.name),
)
Interactive Tools for This Topic
FAQ
- Does `top_k` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- How does the code behave when input is bad?
- `ValueError` is raised at the guard (`k < 0`), so invalid state never reaches the main logic.
- How do you run Top-K Selection with a Bounded Heap?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.