Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python exercise: select the highest scores with stable tie order

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A stable top-k selection returns the k greatest scored records while preserving their original order among equal scores.

Download Python source kit

Operation contract

The review queue contains bounded integer scores and receipt IDs. The function validates the requested count and each record, sorts by descending score and original position, and returns the first k identifiers. A tie between R41 and R42 keeps their input order. The input list remains unchanged, which makes the ownership contract visible.

Failure and ownership boundary

A heap can reduce work when k is much smaller than n, but its tie and replacement policy must be defined before substituting it. A score does not confer authorization to act on the receipt. Python heapq top-k: define ties before ranking frequencies, Python sorting: stable keys, independent output and explicit tie rules and Python rich comparison: return NotImplemented for unsupported operands provide the comparison.

Working program

python
def top_receipts(records, count):
    if type(records) is not list or len(records) > 100 or type(count) is not int or not 0 <= count <= len(records):
        raise ValueError("bounded selection")
    if any(type(row) is not tuple or len(row) != 2 or type(row[0]) is not str or type(row[1]) is not int or not 0 <= row[1] <= 100 for row in records):
        raise ValueError("receipt record")
    ranked = sorted(enumerate(records), key=lambda item: (-item[1][1], item[0]))
    return [row[0] for _, row in ranked[:count]]

queue = [("R41", 8), ("R42", 8), ("R43", 9)]
print(top_receipts(queue, 2))
print(queue)
try:
    top_receipts(queue, True)
except ValueError:
    print("boolean count rejected")

Output

Output
['R43', 'R41']
[('R41', 8), ('R42', 8), ('R43', 9)]
boolean count rejected

Costs and limits

Sorting n records costs O(n log n) time and O(n) result/index storage in this implementation. The 100-record cap bounds the fixture; a streaming top-k implementation needs a separately tested tie policy.

Common Mistakes

  • A plain heap replacement may reorder equal scores.
  • Validate count before slicing; bool is not an acceptable count.

Connected lessons

Python heapq top-k: define ties before ranking frequencies, Python sorting: stable keys, independent output and explicit tie rules, Python rich comparison: return NotImplemented for unsupported operands.

python
stable-top-k-exercise
Storage details