Def fib (n, sum) :
If n & lt; 1:
Return the sum
The else:
Return fib (n - 1, sum + n)
C=998
Print (fib (c, 0))
It can work to n=997, then it will break and spit out "beyond comparison of maximum recursion depth" RuntimeError. This is just a stack overflow? Is there a way to solve it?
CodePudding user response:
A prevent stack overflow, yes. Python (or, more precisely, retaining implementation) not optimize the tail recursion, and unlimited recursive cause stack overflow. You can use the sys. Check getrecursionlimit recursive limit and use sys. Setrecursionlimit change the recursive limit, but it is very dangerous - standard limit a bit conservative, but Python stack frame can be very large.Python is not a functional language, tail recursion is not a particularly effective technology. If possible, iteratively rewriting algorithm is usually a better idea.
CodePudding user response: