How would I efficiently find all the possible combinations of n
positive integers adding up to a given number k
in Python?
I know I could solve this by filtering all the possible combinations:
import itertools
def to_sum_k(n, k):
for i in itertools.product(range(1, k - n + 2), repeat=n):
if sum(i) == k:
yield i
print(list(to_sum_k(3, 5)))
# [(1, 1, 3), (1, 2, 2), (1, 3, 1), (2, 1, 2), (2, 2, 1), (3, 1, 1)]
I have seen something similar has been discussed in abstract way here, but I do not see a simple way of translating this into code.
Also, I would prefer an iterative solution over a recursive one.