查找给定数字的2个数字的所有可能组合/分区

时间:2014-11-08 01:42:40

标签: python python-2.7

我在互联网上找到了这段代码(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 []

我想知道是否有人能找到一种方法来解决答案,只有两位数的答案?

例如:我输入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]]

3 个答案:

答案 0 :(得分:1)

由于您只需要长度为2的分区(以及每个分区的元素的产品),我们可以使用更简单的方法:

#! /usr/bin/env python

''' Find pairs of positive integers that sum to n, and their product '''

def part_prod(n):
    parts = [(i, n-i) for i in xrange(1, 1 + n//2)]
    print parts    
    print '\n'.join(["%d * %d = %d" % (u, v, u*v) for u,v in parts])


def main():    
    n = 10
    part_prod(n)

if __name__ == '__main__':
    main()

<强>输出

[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]
1 * 9 = 9
2 * 8 = 16
3 * 7 = 21
4 * 6 = 24
5 * 5 = 25

答案 1 :(得分:0)

您可以使用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)]

答案 2 :(得分:0)

仅使用列表理解而不使用itertools

num = 10
[[x, y] for x in range(1, num) for y in range(1, num) if x + y == num and x <= y]

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