Python, by default, allows you to have a maximum depth equal to 1000 within the recursion; when this value is exceeded, the quoted error will be issued.
Runtimeerror: Maximum recursion Depth exceeded.
You can check the exact value on your server through the library sys
, with the function getrecursionlimit
:
import sys
print(sys.getrecursionlimit())
You can also change this value with the function setrecursionlimit
:
sys.setrecursionlimit(2000)
The maximum value, according to the documentation, that you can set will depend on the platform limitations where you are running the code; and even if it is a very high value, there will always be a value that exceeds the maximum depth. There’s no way out of this with recursion.
However, a fairly simple solution is to calculate the Fibonacci sequence using a generator:
def fibonacci(n):
a, b = 1, 1
yield a
for _ in range(1, n):
a, b = b, a+b
yield a
But as you have no interest in getting the sequence itself, but rather the nth sequence term, we can generate an iterator that will run through our generator in the interval we want, that is, in the nth term. We do this using the function islice
library itertools
:
import itertools
def nth_value(n):
iterator = itertools.islice(fibonacci(n), n-1, None)
return next(iterator)
Staying:
import itertools
def fibonacci(n):
a, b = 1, 1
yield a
for _ in range(1, n):
a, b = b, a+b
yield a
def nth_value(n):
return next(itertools.islice(fibonacci(n), n-1, n))
See working on Ideone | Repl.it | Wolfram Alpha
Python, by default, allows a maximum depth of 1000 in recursion. Do you really need to calculate for such high values or is it a workout exercise?
– Woss
I thought I could calculate for all the numbers but I went to test and returned it.I want to change the code to work for any number
– Manuel Jose
Recursively it will not be possible. There will always be values that will burst the maximum recursive depth.
– Woss
How do I allocate more resources to speed up the calculation of Fibonacci expression? Type the cpu has almost 85% inactivity and it is only using 10% for code execution
– Manuel Jose