【问题标题】:Python: Find all possible combinations of parts of a given numberPython:查找给定数字部分的所有可能组合
【发布时间】:2016-06-03 14:20:23
【问题描述】:

我正在解决一个难题。假设我有一个正整数,比如说“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

等等。

【问题讨论】:

  • 8 = 8 算不算?
  • 没有,但如果它出现在输出中,没问题。

标签: python-3.x math


【解决方案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]

【讨论】:

  • 谢谢,这对我有很大帮助:)
【解决方案2】:
【解决方案3】:

添加到刚刚错过的 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]]

【讨论】:

  • @V.Petretto 如果解决了您的问题,请接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多