Python:查找给定数字各部分的所有可能组合 [英] Python: Find all possible combinations of parts of a given number

查看:249
本文介绍了Python:查找给定数字各部分的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am solving a puzzle. Suppose I have a positive integer, let's say "8" (it could be any positive integer).

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

How can I create an algorithm to generate the all possible sums of positive integer that will equate to my integer? For example:

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

以此类推.

推荐答案

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

You may find this code useful:

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]

这篇关于Python:查找给定数字各部分的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆