Pav Ametvic - 1 year ago 87

Python Question

Consider this basic recursion in Python:

`def fibonacci(number):`

if number == 0: return 0

elif number == 1:

return 1

else:

return fibonacci(number-1) + fibonacci(number-2)

Which makes sense according to the (n-1) + (n-2) function of the Fibonacci series.

How does Python execute recursion that contains another recursion not within but inside the same code line? Does the 'finobacci(number-1)' complete all the recursion until it reaches '1' and then it does the same with 'fibonacci(number-2)' and add them?

For comparison, the following recursive function for raising a number 'x' into power 'y', I can understand the recursion, def power calling itself until y==0 , since there's only one recursive call in a single line. Still shouldn't all results be '1' since the last command executed is 'return 1' when y==0, therefore x is not returned?

`def power(x, y):`

if y == 0:

return 1

else:

return x*power(x, y-1)

Answer Source

In the expression `fibonacci(number-1) + fibonacci(number-2)`

the first function call will have to complete before the second function call is invoked.

So, the whole recursion stack for the first call has to be complete before the second call is started.