我在网上找到这个代码(Find all possible subsets that sum up to a given number

def partitions(n):
        if n:
            for subpart in partitions(n-1):
                yield [1] + subpart
                if subpart and (len(subpart) < 2 or subpart[1] > subpart[0]):
                    yield [subpart[0] + 1] + subpart[1:]
        else:
            yield []

我想知道是否有人能找到一种方法,只找出答案,那是2位数的加法?
例如:我输入10。它给了我:
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 2, 2, 2], [1, 1, 2, 2, 2, 2], [2, 2, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 3], [1, 1, 1, 1, 1, 2, 3], [1, 1, 1, 2, 2, 3], [1, 2, 2, 2, 3], [1, 1, 1, 1, 3, 3], [1, 1, 2, 3, 3], [2, 2, 3, 3], [1, 3, 3, 3], [1, 1, 1, 1, 1, 1, 4] , [1, 1, 1, 1, 2, 4], [1, 1, 2, 2, 4], [2, 2, 2, 4], [1, 1, 1, 3, 4], [1, 2, 3, 4], [3, 3, 4], [1, 1, 4, 4], [2, 4, 4], [1, 1, 1, 1, 1, 5], [1, 1, 1, 2, 5], [1, 2, 2, 5], [1, 1, 3, 5], [2, 3, 5], [1, 4, 5], [5, 5], [1, 1, 1, 1, 6], [1, 1, 2 , 6], [2, 2, 6], [1, 3, 6], [4, 6], [1, 1, 1, 7], [1, 2, 7], [3, 7], [1, 1, 8], [2, 8], [1, 9], [10]]

我只希望它能:
[[5, 5], [4, 6], [3, 7], [2, 8], [1, 9]]

最佳答案

您可以使用itertools.combinations_with_replacement

from itertools import combinations_with_replacement

n = 10
print([x for x in combinations_with_replacement(range(1,n), 2) if sum(x) == n])

[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]

关于python - 查找给定数字的2个数字的所有可能组合/分区,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26812803/

10-12 18:54