I was working on a problem where I'm finding all k-digit numbers whose digits sum up the given n.
I found how to do this and approach it as Integer Partitioning problem, however I would like to be able to only input n and k numbers (without the max_element) but when I try to delete it from the code it doesn't seem to work anymore.
How can I change that plus reverse it?
def c(n, k, max_element):
allowed = range(max_element, 0, -1)
def helper(n, k, t):
if k == 0:
if n == 0:
yield t
elif k == 1:
if n in allowed:
yield t + (n,)
elif 1 * k <= n <= max_element * k:
for v in allowed:
yield from helper(n - v, k - 1, t + (v,))
return helper(n, k, ())
for p in c(5, 3, 3):
print(p)
I tried using the reversed method but apparently it doesn't work in the generator.
Result:
(3, 1, 1)
(2, 2, 1)
(2, 1, 2)
(1, 3, 1)
(1, 2, 2)
(1, 1, 3)
Expected result:
113 122 131 212 221 311