Python – Sort by Factor count
Last Updated :
28 Apr, 2023
Given element list, sort by factor count of each element.
Input : test_list = [12, 100, 22]
Output : [22, 12, 100]
Explanation : 3, 5, 8 factors respectively of elements.
Input : test_list = [6, 11]
Output : [11, 6]
Explanation : 1, 4 factors respectively of elements.
Method #1 : Using sort() + len() + list comprehension
In this, we perform task of sorting using sort(), and len() and list comprehension is used for task of getting the count of factors.
Python3
def factor_count(ele):
return len ([ele for idx in range ( 1 , ele) if ele % idx = = 0 ])
test_list = [ 12 , 100 , 360 , 22 , 200 ]
print ( "The original list is : " + str (test_list))
test_list.sort(key = factor_count)
print ( "Sorted List : " + str (test_list))
|
Output:
The original list is : [12, 100, 360, 22, 200]
Sorted List : [22, 12, 100, 200, 360]
Time Complexity: O(nlogn) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1) additional space is not needed
Method #2 : Using lambda + sorted() + len()
In this, task of sorting is done using sorted(), and lambda function is used to feed to sorted to get factors.
Python3
test_list = [ 12 , 100 , 360 , 22 , 200 ]
print ( "The original list is : " + str (test_list))
res = sorted (test_list, key = lambda ele: len (
[ele for idx in range ( 1 , ele) if ele % idx = = 0 ]))
print ( "Sorted List : " + str (res))
|
Output:
The original list is : [12, 100, 360, 22, 200]
Sorted List : [22, 12, 100, 200, 360]
Method #3: Using a dictionary to store factor counts and sort by value
Algorithm:
Define an empty dictionary factor_counts.
Iterate over the elements of the input list test_list and for each element ele:
a. Define a variable count to store the number of factors of ele.
b. Iterate over the range from 1 to ele, inclusive, and increment count for each factor of ele.
c. Add a key-value pair to factor_counts with key ele and value count.
Sort test_list by factor count using the factor_counts dictionary. To do this, pass a lambda function to the sorted() function as the key parameter, which returns the value of the corresponding key-value pair in factor_counts for each element in test_list.
Return the sorted list.
Python3
test_list = [ 12 , 100 , 360 , 22 , 200 ]
print ( "The original list is : " + str (test_list))
factor_counts = {}
for ele in test_list:
count = 0
for idx in range ( 1 , ele + 1 ):
if ele % idx = = 0 :
count + = 1
factor_counts[ele] = count
res = sorted (test_list, key = lambda ele: factor_counts[ele])
print ( "Sorted List : " + str (res))
|
Output
The original list is : [12, 100, 360, 22, 200]
Sorted List : [22, 12, 100, 200, 360]
Time complexity: O(n^2), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Share your thoughts in the comments
Please Login to comment...