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.

PythonData Integrity

Code

snippet
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()