Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative order of elements in list

I'm writing a function that takes in a list of integers and returns a list of relative positioned elements.

That is to say, if my input into said function is [1, 5, 4] the output would be [0, 2, 1], since 1 is the lowest element, 5 is the highest and 4 in the middle, all elements are unique values, or a set()

But code speaks, the function i have so far is

def relative_order(a):
    rel=[]
    for i in a:
        loc = 0
        for v in a:
            if i > v:
                loc += 1
        rel.append(loc)
    return rel

It does work, but since i'm sending big lists into this function, and i have to compare each element to all elements in each iteration it's taking ~5sec with a list of 10.000 elements.

My question is how can i improve the speed on said function and maybe be a bit more Pythonic, i tried comprehension lists, but my Python skills are lacking and i only came up with an imperative way of implementing this problem.

like image 428
Ólafur Aron Avatar asked Jul 20 '13 23:07

Ólafur Aron


1 Answers

This can be written as a list comprehension like this:

lst = [1, 5, 4]
s = sorted(lst)    
[s.index(x) for x in lst]
=> [0, 2, 1]

And here's another test, using @frb's example:

lst = [10, 2, 3, 9]
s = sorted(lst)    
[s.index(x) for x in lst]
=> [3, 0, 1, 2]
like image 53
Óscar López Avatar answered Nov 05 '22 07:11

Óscar López