How to count and print triplets from a list with sum smaller than a given value in Python

1 Answer

0 votes
def CountAndPrintAllTripletsSmallerThanSum(lst, summ):
    size = len(lst)
    count = 0
    
    for i in range(size - 2):
        for j in range(i + 1, size - 1):
            for k in range(j + 1, size):
                if lst[i] + lst[j] + lst[k] < summ:
                    count += 1
                    print(count, ": ", lst[i], lst[j], lst[k])
                   
    return count
   
 
lst = [4, 5, 2, 8, 1, 3, 8, 7, 10]
summ = 11
 
print("Number of Triplets = " , CountAndPrintAllTripletsSmallerThanSum(lst, summ))




'''
run:

1 :  4 5 1
2 :  4 2 1
3 :  4 2 3
4 :  4 1 3
5 :  5 2 1
6 :  5 2 3
7 :  5 1 3
8 :  2 1 3
9 :  2 1 7
Number of Triplets =  9

'''

 



answered Sep 16, 2022 by avibootz
...