I'm working on a checkio.org problem and I've built a solution that uses recurssion, except when it runs on the 8th test I get this error:
RuntimeError: maximum recursion depth exceeded while calling a Python object, count_gold, 16, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29, count_gold, 29,
I truncated the end off, but it continues for a good amount of time. I think this is a fundamental misunderstanding I have about the way recursion works. Initially I was very reluctant to post my code since I don't want to give away answers, but I think if I don't link the problem, then my code will just be lost in obscurity. So here we go:
def mystery_function(pyramid, perm=0, lastmax=0, result = [], running=False):
if not running:
result = []
bitstr = bin(perm).zfill(len(pyramid)+1)
bitstr = bitstr.replace("b","")
j, newmax = 0, 0
for i in range(len(pyramid)):
j += int(bitstr[i])
newmax += pyramid[i][j]
maxpermute = "1"*(len(pyramid))
result.append(newmax)
if newmax < lastmax:
nextmax = lastmax
else:
nextmax = newmax
if perm < int(maxpermute,2):
mystery_function(pyramid, perm+1, nextmax, result, True)
return max(result)
So like I said, I think the problem is that I just simply don't fully understand recursion. I read this post: Python RuntimeError: maximum recursion depth exceeded but it doesn't seem to apply because my recursion will break down to the base case and stop.
Any ideas? For those interested (and know the problem based off my function), the recursion fails on test 8.
NOTE: in the function, "pyramid" is a tuple of tuples between 1 and 20 tuples long. We are supposed to travel through the "pyramid" to find that path that yields the largest sum and return that sum