python详尽的组合

问题描述 投票:0回答:3

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

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

python iterator combinations
3个回答
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)

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)

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)]
© www.soinside.com 2019 - 2024. All rights reserved.