Python | Finding relative order of elements in list
Last Updated :
25 Apr, 2023
Sometimes we have an unsorted list and we wish to find the actual position the elements could be when they would be sorted, i.e we wish to construct the list which could give the position to each element destined if the list was sorted. This has a good application in web development and competitive programming domain. Let’s discuss certain ways in which this can be done. Method #1 : Using sorted() + index() + list comprehension All the above function can combine to achieve this particular task. The sorted function returns the sorted order and the indexing is done by the index function. List comprehension does the task of doing for whole list elements and integrating both tasks.
Python3
test_list = [ 6 , 3 , 1 , 2 , 5 , 4 ]
print ("The original list is : " + str (test_list))
temp = sorted (test_list)
res = [temp.index(i) for i in test_list]
print ("The relative ordering list is : " + str (res))
|
Output :
The original list is : [6, 3, 1, 2, 5, 4]
The relative ordering list is : [5, 2, 0, 1, 4, 3]
Time Complexity: O(nlogn), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the test list
Method #2 : Using map() + enumerate() + dictionary comprehension + sorted() The dictionary comprehension is used in place of list comprehension and the sorted list is formed and the index of actual ordering in sorted list are traversed using enumerate to have key-value pair and then are get by map for all the indices in list.
Python3
test_list = [ 6 , 3 , 1 , 2 , 5 , 4 ]
print ("The original list is : " + str (test_list))
temp = {val: key for key, val in enumerate ( sorted (test_list))}
res = list ( map (temp.get, test_list))
print ("The relative ordering list is : " + str (res))
|
Output :
The original list is : [6, 3, 1, 2, 5, 4]
The relative ordering list is : [5, 2, 0, 1, 4, 3]
Method #3 : Using scipy
Install scipy first using “pip install scipy” command
Here is another approach using the rankdata function from the scipy library:
Python3
from scipy.stats import rankdata
test_list = [ 6 , 3 , 1 , 2 , 5 , 4 ]
print ( "The original list is : " + str (test_list))
res = rankdata(test_list) - 1
print ( "The relative ordering list is : " + str (res))
|
Note that rankdata returns the ranks of the elements in the list, with ties being assigned the average rank of the tied elements. If you want to break ties by assigning the lowest rank to the first element, you can use the method parameter of rankdata and set it to ‘min’.
Output:
The original list is : [6, 3, 1, 2, 5, 4]
The relative ordering list is : [5, 2, 0, 1, 4, 3]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...