I have the following code. It's about as simple as I can make it. Does anyone know of a slick way to turn this recursion into a loop?
The problem is that I can run into a recusion limit. I've thought of some ways to rewrite it, but they're not pretty at all.
My nicest thought at this point is that I could get it into some tail recursion form, but I'm not sure how to do that.
def blackbox(c, i): #This is a different function in production
if i > 5:
return range(0,1)
else:
return range(0,c+i)
def recurse(c, length):
if length == 0:
return [[]]
return [l + [j] for j in blackbox(c, length) for l in recurse(c - j, length - 1)]
Example: recurse(6, 1000) throws an error is way over the recursion limit.
Cool, mostly useless fact: Using range(i, c + 1) for the black box returns all the lists with length length with sum at most c.
EDIT: I'm aware I can memoize the code, but that doesn't fix recursion limit. In this example, memoizing helps the speed a lot, but in my situation it doesn't, so I'm not concerned with it.
EDIT 2: Updated blackbox so the value of recurse(6,1000) is reasonable.