865. Fix top-k retrieval that returns the worst matches
Why it matters Retrieval and sampling code sorts scores all the time. Ascending versus descending is an easy slip that ruins RAG quality without any error.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
top_k_indices(scores, k) should return the indices of the k highest scores, best first. Ties keep the lower index first. If k is larger than the number of scores, return all indices. k = 0 returns an empty list.
Inputs: scores is a list or ndarray of floats, shape (n,). k is an int >= 0.
Return a list of Python ints.
def top_k_indices(scores, k)Example 1
Input: top_k_indices([0.1, 0.9, 0.4, 0.7], 2)
Output: [1, 3]
Example 2
Input: scores = [0.5, 0.5, 0.2], k = 2
Output: [0, 1]
Example 3
Input: scores = [1.0, 2.0], k = 0
Output: []
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Run the example. Are 1 and 3 in the output?
Hint 2
argsort is ascending.
Hint 3
Sort the negated scores with kind='stable'.
Common mistakes
- Using [::-1], which reverses tie order.
- Returning scores instead of indices.
- Returning numpy ints instead of Python ints.
Understand the idea
np.argsort sorts ascending, so the first k indices are the worst scores. Sorting -scores with a stable sort gives descending order and keeps ties in index order. Reversing an ascending argsort with [::-1] also gives descending order but breaks the tie rule.
Shapes and data flow
scores: (n,). Output: list of up to k ints.