Consider this basic recursion in Python:
def fibonacci(number):
if number == 0: return 0
elif number == 1:
return 1
else:
return
Matthew and MArtjin are right but I thought I might elaborate:
Python does stuff from left to right whenever it can. Exceptions to this rule are implied by brackets.
in x*power(x, y-1)
: x
is evaluated then power
is evaluated
While in fibonacci(number-1) + fibonacci(number-2)
, fibonacci(number-1)
is evaluated (recursively, til it stops) and then fibonacci(number-1)
is evaluated
def fib(n):
if n <= 1:
return n
else :
return fib(n - 1) + fib(n - 2)
Your second recursion functions does this (example), so 1 will not be returned.
power(2, 3)
2 * power(2, 2)
2 * 2 * power(1,2)
2 * 2 * 2 * power(0,2) # Reaching base case
2 * 2 * 2 * 1
8
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.