I have created a generator using itertools combinations_with_replacement which returns all the combinations of 3 positive integers that sum to n:
def combinations(n):
for combo in combinations_with_replacement([i for i in range(1,n+1)],3):
if sum(combo) == n:
yield(combo)
e.g. combinations(7) returns (1, 1, 5) (1, 2, 4) (1, 3, 3) (2, 2, 3)
Unfortunately this quickly becomes very slow with larger values of n. Is there an alternative way of doing this which is more efficient? I have tried using for loops although every time I get duplicate combinations.
Thanks in advance!