One of the problem that is basically a subproblem for many complex problem, finding numbers greater than certain number in list in python and performing it’s summation , is commonly encountered and this particular article discusses possible solutions to this particular problem.
Method 1 : Naive method :
The most common way this problem can be solved is using loop and just summing the occurrences of elements that are greater than the given number K.
# Python 3 code to demonstrate
# K Greater Elements Summation
# using naive method
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
# initializing k
k = 4
# printing list
print ("The list : " + str(test_list))
# using naive method
# K Greater Elements Summation
sum = 0
for i in test_list :
if i > k :
sum = sum + i
# printing the result
print ("The summation greater than 4 : " + str(sum))
Method 2 : Using list comprehension :
This method achieves this task in similar way, but in more concise manner. List comprehension always lower the lines of codes in the program even though runs a similar approach in background.
# Python 3 code to demonstrate
# K Greater Elements Summation
# using list comprehension
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
# initializing k
k = 4
# printing list
print ("The list : " + str(test_list))
# using list comprehension
# K Greater Elements Summation
sum = sum([i for i in test_list if i > k])
# printing the result
print ("The summation greater than 4 : " + str(sum))