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

51,870 answers

573 users

How to add to 2D list the total equal to Y combinations of X numbers of list of N numbers in Python

1 Answer

0 votes
from itertools import combinations 

N = 11
lst = list(range(1, N))

X = 5
comb = combinations(lst, X) 
  
two_d = [[] for i in range(20)] 

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

 



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