argsort and Taking the Top K
~10 mincode completion
Write top_k_indices(scores, k) that returns the indices of the k highest scores, highest first.
For [0.2, 0.9, 0.5] with k=2 it returns [1, 2].
Examples
Returns indices, highest score first
- Input
- top_k_indices([0.2, 0.9, 0.5], 2)
- Output
- [1, 2]
k=1 returns just the single best index
- Input
- top_k_indices([3, 1, 4, 1], 1)
- Output
- [2]
k equal to the length returns a full ranking
- Input
- top_k_indices([10, 30, 20], 3)
- Output
- [1, 2, 0]
Hints
Hint 1
You need the index of the extreme value, not the value itself.
Hint 2
Return indices rather than values.
Requirements
scores: a 1-D array of numbersk: how many indices to returnReturn an array of k indices, ordered from highest score to lowest.
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Try similar problems(4)
Where this shows up
~10 min
••••••••••••••••
8 employers weight this skill
3 quant funds, 2 big tech firms, 1 frontier lab, 1 autonomy company, 1 enterprise vendor. Top match scores 81.
Python
import numpy as np
def top_k_indices(scores, k):
"""
Find the positions of the k largest scores.
Args:
scores: a 1-D array of numbers
k: how many indices to return
Returns:
An array of k indices, ordered from highest score to lowest.
"""
# YOUR CODE HERE
pass