Python Program to assign each list element value equal to its magnitude order
Last Updated :
08 Mar, 2023
Given a list, the task is to write a Python program to assign each element value equal to its magnitude order.
Input : test_list = [8, 3, 5, 8, 1, 5, 4]
Output : [4, 1, 3, 4, 0, 3, 2]
Explanation : 8 is 5th maximum hence 4 [starting from 0th index] is assigned to it.
Input : test_list = [3, 2, 0]
Output : [2, 1, 0]
Explanation : 3 is 3rd maximum as 2 is assigned.
Method 1 : Using set() + zip() + dict() + list comprehension
In this, we perform task of mapping sorted index of set converted list to values using zip(), and then convert to dictionary of value mapped to values. Then list comprehension is used to ordering in list.
Python3
test_list = [ 8 , 3 , 5 , 8 , 1 , 5 , 4 ]
print ( "The original list is : " + str (test_list))
ord_dict = dict ( zip ( list ( set (test_list)),
range ( len ( set (test_list)))))
res = [ord_dict[ele] for ele in test_list]
print ( "Relative size ordered list : " + str (res))
|
Output:
The original list is : [8, 3, 5, 8, 1, 5, 4]
Relative size ordered list : [4, 1, 3, 4, 0, 3, 2]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2 : Using sorted() + set() + index() + list comprehension
In this, we perform task of conversion to set and then sort, index mapping to order is done using index() and list comprehension.
Python3
test_list = [ 8 , 3 , 5 , 8 , 1 , 5 , 4 ]
print ( "The original list is : " + str (test_list))
ord_dict = list ( set (test_list))
res = [ord_dict.index(ele) for ele in test_list]
print ( "Relative size ordered list : " + str (res))
|
Output:
The original list is : [8, 3, 5, 8, 1, 5, 4]
Relative size ordered list : [4, 1, 3, 4, 0, 3, 2]
Time Complexity: O(n*nlogn) where n is the number of elements in the list “test_list”. The sorted() + set() + index() + list comprehension is used to perform the task and it takes O(n*nlogn) time.
Auxiliary Space: O(n) additional space of size O(n) is required
Share your thoughts in the comments
Please Login to comment...