Python – Count % K elements
Last Updated :
13 Apr, 2023
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization. Lets discuss certain ways in which the task of checking count of numbers divisible to K can be achieved.
Method #1 : Using sum() + generator expression This method uses the trick of adding 1 to the sum whenever the generator expression returns true. By the time list gets exhausted, summation of count of numbers matching % K is returned.
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 ]
print ("The original list is : " + str (test_list))
K = 3
res = sum ( 1 for i in test_list if i % K ! = 0 )
print ("The number of % K elements: " + str (res))
|
Output :
The original list is : [3, 5, 1, 6, 7, 9]
The number of % K elements: 3
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(1) additional space is not needed
Method #2 : Using sum() + map() map() does the task almost similar to the generator expression, difference is just the internal data structure employed by it is different hence more efficient.
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 ]
print ("The original list is : " + str (test_list))
K = 3
res = sum ( map ( lambda i: i % K ! = 0 , test_list))
print ("The number of % K elements: " + str (res))
|
Output :
The original list is : [3, 5, 1, 6, 7, 9]
The number of % K elements: 3
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is required
Method #3 : Using filter()
The filter() function returns the elements of an iterable that match the condition specified.
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 ]
print ( "The original list is : " + str (test_list))
K = 3
res = len ( list ( filter ( lambda i: i % K ! = 0 , test_list)))
print ( "The number of % K elements: " + str (res))
|
Output
The original list is : [3, 5, 1, 6, 7, 9]
The number of % K elements: 3
Time Complexity: O(n) where n is the number of elements in the string list. The filter() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the test list.
Share your thoughts in the comments
Please Login to comment...