Python 中的组合函数

Combination function in Python

我想写一个函数,它给我一个数字组合(给定数量)作为系数,它们的总和给我们 4。

假设给定的变量数是2。所以我们需要说找到a+b=4的组合。它将是 [1,3], [2,2], [3,1], [0,4], [4,0]。或者如果给定的变量数是 3,那么需要找到 a+b+c=4 的组合,这将是 [1,2,1], [1,1,2],等等

我该怎么做?

您可以使用此代码

def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
    return
indices = list(range(r))
yield tuple(pool[i] for i in indices)
while True:
    for i in reversed(range(r)):
        if indices[i] != i + n - r:
            break
    else:
        return
    indices[i] += 1
    for j in range(i+1, r):
        indices[j] = indices[j-1] + 1
    yield tuple(pool[i] for i in indices)

您尝试解决的问题在数论中被称为 Integer Partitioning. Refer to this answer for a possible solution. This 数学交流也可以帮助您更多地了解问题背后的数学原理。