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 sum that match the particular condition to have a distinguish which to not match for further utilization. Lets discuss certain ways in which this task can be achieved.
Method #1 : Using loop
This is brute force method to perform this particular task. In this, we iterate list, find elements that match a particular condition and take sum.
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 ]
print ( "The original list is : " + str (test_list))
res = 0
for ele in test_list:
if ele % 2 ! = 0 :
res = res + ele
print ( "The sum of odd elements: " + str (res))
|
Output : The original list is : [3, 5, 1, 6, 7, 9]
The sum of odd elements: 25
Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list
Method #2 : Using sum() + generator expression
This method uses the trick of adding element to the sum whenever the generator expression returns true. By the time list gets exhausted, summation of numbers matching a condition is returned.
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 ]
print ( "The original list is : " + str (test_list))
res = sum (i for i in test_list if i % 2 ! = 0 )
print ( "The sum of odd elements: " + str (res))
|
Output : The original list is : [3, 5, 1, 6, 7, 9]
The sum of odd elements: 25
Time Complexity: O(n) where n is the number of elements in the string list. The sum() + generator expression is used to perform the task and it takes O(n) time.
Auxiliary Space: O(1) constant additional space is required.
Method #3: Using filter()+list()+sum()+ lambda functions
Python3
test_list = [ 3 , 5 , 1 , 6 , 7 , 9 ]
print ( "The original list is : " + str (test_list))
res = sum ( list ( filter ( lambda x: x % 2 ! = 0 , test_list)))
print ( "The sum of odd elements: " + str (res))
|
OutputThe original list is : [3, 5, 1, 6, 7, 9]
The sum of odd elements: 25
Time Complexity: O(N)
Auxiliary Space: O(N)