Python | Summation of first N matching condition
Last Updated :
09 Apr, 2023
Summation of elements in list can be performed using many inbuilt function. Normal summation functions have many applications in various domains. This article discusses to sum just the first N occurrences of elements matching particular condition.
Method #1 : Naive Method We can sum the elements that are matching condition, after N occurrences of elements have been done and we can stop the operation. Code below demonstrates the same.
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 , 8 , 5 ]
print ("The original list is : " + str (test_list))
counter = 1
res = 0
for i in test_list:
if counter < = 3 and (i % 2 ! = 0 ):
res = res + i
counter = counter + 1
print ("The filtered list is : " + str (res))
|
Output :
The original list is : [3, 5, 1, 6, 7, 9, 8, 5]
The filtered list is : 9
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(1), as we’re using constant additional space.
Method #2 : Using sum() + list comprehension This is different and elegant way to perform this particular task. It filters out all the numbers that are less than equal N and sums according to condition. This is one liner and preferred method to achieve this task.
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 , 8 , 5 ]
print ("The original list is : " + str (test_list))
res = sum ([i for i in test_list if i % 2 ! = 0 ][: 3 ])
print ("The filtered list is : " + str (res))
|
Output :
The original list is : [3, 5, 1, 6, 7, 9, 8, 5]
The filtered list is : 9
Time Complexity: O(n) where n is the number of elements in the string list. The sum() + list comprehension is used to perform the task and it takes O(n) time.
Auxiliary Space: O(1) constant additional space is required.
Share your thoughts in the comments
Please Login to comment...