I am trying to write a recursive multinacci (basically fibonacci numbers except the rabbits produce k pairs instead of 1 pair with each breeding cycle) function and I want it to work with all n. Here is my code so far:
from functools import lru_cache
from sys import getrecursionlimit, setrecursionlimit
def fibnum(n, k=1):
"""Returns the nth fibonacci number of order k"""
# check if recursionlimit needs increasing
return _fibnum(n, k)
@lru_cache(maxsize=None)
def _fibnum(n, k):
if n <= 0:
return 0
if n == 1:
return 1
return _fibnum(n-1, k) + k * _fibnum(n-2, k)
A few notes about the code: the first function is a wrapper around the second so as to the description text look right. The second function is memoized, which increases performance drastically.
I've noticed that when I try to find increasing values of fibnum in order (100, 400, 1000 etc.) I can get around the recursion limit since the memoization shortcuts the recursion. I want to be able to run my function for any number right off the bat. I've tried testing the bounds of the recursion limit for n and then setting the recursion limit to that, but the only one that seemed to work was n2, but that seems too high of a limit.
Any suggestions?
Note: at a later point, I would like to add a lifespan to the formula (which is basically subtract out fibnum(n- life_span, k)). How would this affect the recursion depth needed?
try, catch theRuntimeErrorand double the recursion limit then (up to some larger max - eventually you'll have to give in!)lru_cacheinfunctools(notitertools), and doesn't it preserve documentation (although admittedly not signature)?