Find all possible combinations / sections of 2 numbers for a given number
I found this code on the internet ( 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 []
I was wondering if anyone could find a way to pull only answers that are two digits long from an answer?
For example: I type at 10. He gives me:
[[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]]
I would like it to only give:
[[5, 5], [4, 6], [3, 7], [2, 8], [1, 9]]
+3
source to share
3 answers
you can use 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)]
0
source to share
Since you only need sections of length 2 (and the products of the elements of each section), we can use a simpler approach:
#! /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()
Output
[(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
source to share