I tried to print out flow of execution of factorial recursion function.
def factorial(n):
space=' '*(4*n)
print(space,'factorial ',n)
if n==0:
print(space,'returning 1')
return 1
else:
recurse=factorial(n-1)
result=n*recurse
print(space,'returning ', result)
return n*recurse
With factorial(2) result will be correct:
factorial 2
factorial 1
factorial 0
returning 1
returning 1
returning 2
2
But when I don't use variable recurse=factorial(n-1):
def factorial(n):
space=' '*(4*n)
print(space,'factorial ',n)
if n==0:
print(space,'returning 1')
return 1
else:
result=n*factorial(n-1)
print(space,'returning ', result)
return n*factorial(n-1)
then with factorial(2) it printed out different flow:
factorial 2
factorial 1
factorial 0
returning 1
returning 1
factorial 0
returning 1
returning 2
factorial 1
factorial 0
returning 1
returning 1
factorial 0
returning 1
2
My question is: why was there different flow of executions [with and without variable recurse=factorial(n-1)]?
This is due to below extra function call in your code
def factorial(n):
space=' '*(4*n)
print(space,'factorial ',n)
if n==0:
print(space,'returning 1')
return 1
else:
result=n*factorial(n-1)
print(space,'returning ', result)
return n*factorial(n-1) # factorial(n-1) is called second time so that this function is executed once again
You could do as below for similar execution
def factorial(n):
space=' '*(4*n)
print(space,'factorial ',n)
if n==0:
print(space,'returning 1')
return 1
else:
result=n*factorial(n-1)
print(space,'returning ', result)
return result