If I call fib(5) then how many times does it compute the value fib(2)?
Three. You can see for yourself if you add a print statement.
def fib(n):
if n == 1 or n == 0:
return 1
else:
print('Computing fib(%i)...' % n)
return fib(n-1) + fib(n-2)
The output will look like this:
In [4]: fib(5)
Computing fib(5)...
Computing fib(4)...
Computing fib(3)...
Computing fib(2)...
Computing fib(2)...
Computing fib(3)...
Computing fib(2)...
Out[4]: 8
This also gives you some idea of the internal structure of the recursion.
To figure out fib(5)
, it has to return fib(n-1) + fib(n-2)
, which is fib(4) - fib(3)
. It has to compute fib(4)
first.
To figure out fib(4)
, it needs fib(3)
and fib(2)
. It does fib(3)
first.
To figure out fib(3)
, it does fib(2)
and fib(1)
. It does fib(2)
first.
To figure out fib(2)
, it needs fib(1)
and fib(0)
. It does fib(1)
first.
Finally, we return without another function call! fib(1)
gives us an integer 1 and we can get back to adding to fib(0)
, which also immediately returns 1.
That addition completes the return of fib(2)
. Remember this call was part of figuring out fib(3)
, so now we need the last half of that addition. It is fib(1)
so we return immediately and complete the call.
Then we can figure out the last half of fib(3)
, which means we compute fib(2)
again. Both parts of this immediately return and we get the answer.
Now we're back out in fib(4)
. The first part of it has returned so we need to compute the next half, which is fib(3)
. This is computed exactly as before.
Hopefully now the stack of Computing fib(n)...
makes a bit more sense. :)