Python:查找给定数字部分的所有可能组合

时间:2016-06-03 14:20:24

标签: python-3.x math

我正在解决一个难题。假设我有一个正整数,让我们说" 8" (它可以是任何正整数)。

如何创建一个算法来生成所有可能的正整数和等于我的整数?例如:

8 = 7+1
8 = 6+2
8 = 6+1+1
8 = 5+3
8 = 5+2+1
8 = 5+1+1+1
8 = 4+4
8 = 4+3+1
8 = 4+2+2
8 = 4+2+1+1

等等。

3 个答案:

答案 0 :(得分:1)

您可能会发现此代码很有用:

def sum_to_n(n, size, limit=None):
    """Produce all lists of `size` positive integers in decreasing order
    that add up to `n`."""
    if size == 1:
        yield [n]
        return
    if limit is None:
        limit = n
    start = (n + size - 1) // size
    stop = min(limit, n - size + 1) + 1
    for i in range(start, stop):
        for tail in sum_to_n(n - i, size - 1, i):
            yield [i] + tail

for partition in sum_to_n(6, 3):
    print (partition)

[2, 2, 2]
[3, 2, 1]
[4, 1, 1]

答案 1 :(得分:0)

答案 2 :(得分:0)

添加到错过了一点点的Cid-EL迭代:

def sum_to_n(n, size, limit=None):
    """Produce all lists of `size` positive integers in decreasing order
    that add up to `n`."""
    if size == 1:
        yield [n]
        return
    if limit is None:
        limit = n
    start = (n + size - 1) // size
    stop = min(limit, n - size + 1) + 1
    for i in range(start, stop):
        for tail in sum_to_n(n - i, size - 1, i):
            yield [i] + tail

def n_sum(n):
    ret_list = []
    for s in range(1, n):
        for m in sum_to_n(n, s):
            ret_list.append(m)
    ret_list.append([1]*n)
    return ret_list

# You would use this as a command:
>>> n_sum(8)
[[8], [4, 4], [5, 3], [6, 2], [7, 1], [3, 3, 2], [4, 2, 2], [4, 3, 1], [5, 2, 1], [6, 1, 1], [2, 2, 2, 2], [3, 2, 2, 1], [3, 3, 1, 1], [4, 2, 1, 1], [5, 1, 1, 1], [2, 2, 2, 1, 1], [3, 2, 1, 1, 1], [4, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1], [3, 1, 1, 1, 1, 1], [2, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]]