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