I have a list of values, I want to get the ranks of these values in the list x
This is the code that I tried:
x = [4,7,9,10,6,11,3,15,2]
seq = sorted(x, reverse=True)
index = [x.index(v) for v in seq]
and I don't understand why it gives this output : [6, 4, 3, 2, 5, 1, 7, 0, 8] instead of the right order.
EDIT: sorry, the right order is [7,5,3,2,1,4,0,6,8] (decending order of the values in x by index)
EDIT2: I fixed it. Sorry, lack of sleep :p.
You should iterate over the sorted list seq
and find the index of the original list x
instead:
x = [4,7,9,10,6,11,3,15,2]
seq = sorted(x, reverse=True)
index = [x.index(v) for v in seq]
index
becomes:
[7, 5, 3, 2, 1, 4, 0, 6, 8]
Using the index
method in a loop makes the solution unnecessarily O(n^2) in time complexity, however. You should instead consider creating a dict that maps items in x
to their indices, and since the lookup of a dict key costs O(1) in average, doing it in a loop would thus cost only O(n):
x = [4,7,9,10,6,11,3,15,2]
indices = {n: i for i, n in enumerate(x)}
seq = sorted(x, reverse=True)
index = [indices[v] for v in seq]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments