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,928 questions

51,861 answers

573 users

How to find the total equal to Y combinations of X numbers from list of N numbers in Python

1 Answer

0 votes
from itertools import combinations 
   
lst = list(range(1, 11))
X = 5
comb = combinations(lst, X) 

Y = 31
for ol in list(comb):
    sum = 0
    tmp_lst = []
    for n in ol:
       sum += n
       tmp_lst.append(n)
    if (sum == Y):
       print(tmp_lst , "sum =", sum)
 
 
 
'''
run:
 
[1, 3, 8, 9, 10] sum = 31
[1, 4, 7, 9, 10] sum = 31
[1, 5, 6, 9, 10] sum = 31
[1, 5, 7, 8, 10] sum = 31
[1, 6, 7, 8, 9] sum = 31
[2, 3, 7, 9, 10] sum = 31
[2, 4, 6, 9, 10] sum = 31
[2, 4, 7, 8, 10] sum = 31
[2, 5, 6, 8, 10] sum = 31
[2, 5, 7, 8, 9] sum = 31
[3, 4, 5, 9, 10] sum = 31
[3, 4, 6, 8, 10] sum = 31
[3, 4, 7, 8, 9] sum = 31
[3, 5, 6, 7, 10] sum = 31
[3, 5, 6, 8, 9] sum = 31
[4, 5, 6, 7, 9] sum = 31
 
'''

 



answered Dec 8, 2019 by avibootz
edited Dec 9, 2019 by avibootz
...