PY-20

Select the Best k Records with Stable Ties

  • Medium
  • Ordering and Selection
  • Python

Task

Write select_best_k(records, k). Each item in records is a two-item tuple (id, score). Select at most k records with the highest scores.

Return a new list ordered from highest score to lowest score. If two records have the same score, keep them in the order in which they appeared in the input. This is a stable tie rule: compare scores only, and do not use the IDs to break ties. If k is greater than the number of records, return every record in score order. If k is zero or negative, return [].

The input list and its records must not be changed.

Example

The two records scoring 10 remain in their source order ("b" before "c"). The record scoring 6 is outside the first three results.

Your implementation

Edit solution.py and keep this function name and signature:

Return a list containing up to k of the original two-item records. Sort by the numeric score in descending order, preserving source order for equal scores; the IDs are labels, not a secondary ordering key. An empty input or a non-positive k must produce an empty list. Do not print the result, ask for input, or mutate records.