Python – Sort a List by Factor count

PythonServer Side ProgrammingProgramming

When it is required to sort a list by factor count, a method is defined that uses list comprehension and modulus operator along with ‘len’ method to determine the output.

Example

Below is a demonstration of the same −

def factor_count(element):
   return len([element for index in range(1, element) if element % index == 0])

my_list = [121, 1120, 13540, 221, 1400]

print("The list is :")
print(my_list)

my_list.sort(key=factor_count)

print("The result is :")
print(my_list)

Output

The list is :
[121, 1120, 13540, 221, 1400]
The result is :
[121, 221, 13540, 1120, 1400]

Explanation

  • A method named ‘factor_count’ is defined that takes element of list as a parameter, and returns output.

  • Outside the method, a list is defined and displayed on the console.

  • The list is sorted using ‘sort’ method and the key is specified as the previously defined method.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 10:22:49
Advertisements