What is the maximum recursion depth in Python, and how to increase it? -
i have tail recursive function here:
def fib(n, sum): if n < 1: return sum else: return fib(n-1, sum+n) c = 998 print(fib(c, 0))
it works n=997, breaks , spits "maximum recursion depth exceeded in comparison" runtimeerror
. stack overflow? there way around it?
it guard against stack overflow, yes. python (or rather, cpython implementation) doesn't optimize tail recursion, , unbridled recursion causes stack overflows. can change recursion limit sys.setrecursionlimit
, doing dangerous -- standard limit little conservative, python stackframes can quite big.
python isn't functional language , tail recursion not particularly efficient technique. rewriting algorithm iteratively, if possible, better idea.
Comments
Post a Comment