My code is just a sample to demonstrate the technique of indexing off the first 3 elements of the list. You need to adapt that technique to extract the first k elements of your sorted_ids
.
What you are doing is this:
k_idx = sorted_ids[k:]
As I pointed out earlier, what that does is starts at k and takes the rest of the list. That is different than starting at the beginning and stopping at k, right?
Here is some sample code. This is not a solution to your problem. This is just demonstrating the idea of how indexing works. Here’s an example list:
aList = list(range(12))
print(f"aList = {aList}")
aList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Ok, we have a list with 12 elements. Now we index it the way you did:
print(f"aList[4:] = {aList[4:]}")
aList[4:] = [4, 5, 6, 7, 8, 9, 10, 11]
So that does what I said above: it starts at index 4 and gives you the rest of the list. But that’s not what you want in this case, right?
Now watch this:
print(f"aList[0:4] = {aList[0:4]}")
aList[0:4] = [0, 1, 2, 3]
Do you see what that did? It gave us the first 4 elements of the list, right? So which method do you need to apply in this case?