0

I am trying to write a function has input:

given_num=6, n=3

How to return a result of all possible combinations as list with n elements and sum = given_num nested in a list:

[[0,0,6],[0,1,5],[0,2,4],[0,3,3],[0,4,2],[0,5,1],[0,6,0],
[1,0,5],[1,1,4],[1,2,3],[1,3,2],[1, 4,1],[1,5,0],
...
[6,0,0]]

solved, and the possible combination is calculated as

factorial(given_num+n-1)/(factorial(given_num) * factorial(n-1))

  • 3
    did you try anything? What was the problem with it? – Ma0 Jun 08 '18 at 09:00
  • Possible duplicate of [Generate all possible outcomes of k balls in n bins (sum of multinomial / categorical outcomes)](https://stackoverflow.com/questions/37711817/generate-all-possible-outcomes-of-k-balls-in-n-bins-sum-of-multinomial-catego) – Georgy Jun 08 '18 at 09:29
  • @Georgy , thx for the link, the generator solution is time saving for a large given_num or n, considering I am working on a optimization problem. – Robin Larson Jun 11 '18 at 02:50

3 Answers3

1

Here a try using itertools product :

from itertools import product

given_num = 6
n = 3
all_comb = product(range(given_num+1), repeat=n)
final_lst = [i for i in all_comb if sum(i) == given_num]
print(final_lst)
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
0
from itertools import product
import numpy as np

tuples = []
given_num = 6
n = 3

for numbers in product(np.arange(given_num+1), repeat=n):

    if sum(numbers) == given_num:
        tuples.append(numbers)

print(tuples)
Fourier
  • 2,795
  • 3
  • 25
  • 39
0

In case you want to have some fun with recursive functions

def summands(num, N):
    if N==1:
        return [[num]]
    else:
        return [[i] + j for i in range(num+1) for j in summands(num - i, N-1)]
kosnik
  • 2,342
  • 10
  • 23