Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

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
...