python详尽的组合

时间:2018-06-08 08:58:46

标签: python iterator combinations

我正在尝试写一个函数有输入:

given_num=6, n=3

如何将所有可能组合的结果作为列表返回,其中n个元素和sum = given_num嵌套在列表中:

[[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]]

已解决,可能的组合计算为

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

3 个答案:

答案 0 :(得分:1)

尝试使用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)

答案 1 :(得分:0)

pathname

答案 2 :(得分:0)

如果您想要使用递归函数获得一些乐趣

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)]