BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Debug and fix10 of 16 in topic

865. Fix top-k retrieval that returns the worst matches

EasyDebug and fix

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.

Functiondef 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.
Topics
Debug and fix
Similar questions
  • Fix the softmax that returns nanEasy
  • Fix the LayerNorm that normalises the wrong axisEasy
  • Fix the cross-entropy that returns infEasy
  • Fix the F1 score that crashes on empty predictionsEasy
All Debug and fix problems
Report
865 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
import numpy as np
​
def top_k_indices(scores, k):
s = np.asarray(scores, dtype=float)
order = np.argsort(s, kind="stable")
return [int(i) for i in order[:k]]
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS