Python – Elements with factors count less than K


When it is required to display elements with factors count less than K, a method is defined that takes two parameters and uses list comprehension to iterate over the elements and use ‘modulus’ operator to determine the result.

Below is a demonstration of the same −

Example

 Live Demo

def factors(element, K):
   return len([index for index in range(1, element + 1) if element % index == 0]) <= K

my_list = [63, 112, 168, 26, 68]

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

K = 5
print("The value for K is ")
print(K)

my_result = [element for element in my_list if factors(element, K)]

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

Output

The list is :
[63, 112, 168, 26, 68]
The value for K is
5
The result is :
[26]

Explanation

  • A method is defined that takes element and key as parameters, and uses the modulus operator between the element and the index and compares it with 0.

  • This result is then compared with the key and the length of the entire operation is returned as output.

  • A list is defined and displayed on the console.

  • The value for K is defined.

  • A list comprehension is used to iterate over the list, and every row and the method is called by passing the required parameter.

  • This result is assigned to a variable.

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

Updated on: 06-Sep-2021

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements