
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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.
- Related Articles
- Count subarrays with all elements greater than K in C++
- Two Sum Less Than K in Python
- Count all subsequences having product less than K in C++
- Count of alphabets having ASCII value less than and greater than k in C++
- Python Program to remove elements that are less than K difference away in a list
- 8085 program to count number of elements which are less than 0A
- Program to find number of elements in A are strictly less than at least k elements in B in Python
- Count pairs in a sorted array whose product is less than k in C++
- Count pairs with bitwise OR less than Max in C++
- Count ordered pairs with product less than N in C++
- Subarray Product Less Than K in C++
- Count the number of words having sum of ASCII values less than and greater than k in C++
- Program to count number of sublists with exactly k unique elements in Python
- Count of elements whose absolute difference with the sum of all the other elements is greater than k in C++
- Count sub-arrays which have elements less than or equal to X in C++
