I have this simple recursive function, which is calculating the factorial of a number. The result is good and it works like a charm.
def factorial(y):
if y == 0:
return 1
elif y == 1:
return 1
else:
result = y * factorial(y - 1)
print(result)
return result
To understand the process I've added the print(result) function to see the value of the result variable at each iteration of the recursive function.
The output is:
2
6
24
120
I was expecting this output instead :
120
24
6
2
So, why is my recursive function iterating from the lowest number to the highest and not from the highest to the lowest number ?
The inner-most call finishes first, so that one prints first.
The outer-most call is only ready once all the inner calls finish, so it necessarily has to be printed only after the inner calls finish.
Try this for funsies:
def factorial(y, level=0):
if y == 0:
return 1
elif y == 1:
return 1
else:
print(level*" ", "pre-call, y=", y)
result = y * factorial(y - 1, level=level+2)
print(level*" ", "post-call, result=", result)
return result
factorial(5)
Output is:
pre-call, y= 5
pre-call, y= 4
pre-call, y= 3
pre-call, y= 2
post-call, result= 2
post-call, result= 6
post-call, result= 24
post-call, result= 120
The nesting helps show the recursion level.