Python | Above K elements summation
Last Updated :
09 Apr, 2023
Many times we might have problem in which we need to find summation rather than the actual numbers and more often, the result is conditioned.. Let’s discuss certain ways in which this problem can be successfully solved.
Method #1 : Using loop This problem can easily be solved using loop with a brute force approach in which we can just check for the sum as we iterate and append it in a new list as we proceed forward.
Python3
test_list = [ 12 , 10 , 18 , 15 , 8 , 18 ]
print ( "The original list : " + str (test_list))
res = 0
for idx in range ( 0 , len (test_list)) :
if test_list[idx] > 10 :
res + = test_list[idx]
print ( "The summation of elements greater than 10 : " + str (res))
|
Output
The original list : [12, 10, 18, 15, 8, 18]
The summation of elements greater than 10 : 63
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the loop which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using list comprehension + sum() The combination of these two function can also perform this particular task efficiently and in one line. The sum function is used to perform summation of elements.
Python3
test_list = [ 12 , 10 , 18 , 15 , 8 , 18 ]
print ( "The original list : " + str (test_list))
res = sum (ele for ele in test_list if ele > 10 )
print ( "The summation of elements greater than 10 : " + str (res))
|
Output
The original list : [12, 10, 18, 15, 8, 18]
The summation of elements greater than 10 : 63
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #3 : Using filter() + sum()
Python3
def greater_than_10(x):
return x > 10
test_list = [ 12 , 10 , 18 , 15 , 8 , 18 ]
print ( "The original list : " + str (test_list))
res = sum ( filter (greater_than_10, test_list))
print ( "The summation of elements greater than 10 : " + str (res))
|
Output
The original list : [12, 10, 18, 15, 8, 18]
The summation of elements greater than 10 : 63
In Method #3, filter() function is used to filter the elements in the list that satisfy a certain condition and only those elements are passed to the sum() function which then returns the summation of those elements.
Time Complexity: O(n) where n is the size of the list and
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...