Factorial example:
def r_factorial(n):
if n==1:
return n
else:
t=r_factorial(n-1)
t=t*n
return t
print(r_factorial(5))
Why once t=1 the function continue?
The reason the recursion continues after reaching n == 1 is because of how recursive function calls work. Let's break it down step by step.
Understanding Recursive Execution:
Each
recursive call pauses execution until the next recursive call returns a
value. The recursion only stops when it reaches the base case, which is
n == 1. At that point, the function starts returning values back up the
recursive stack.
Step-by-Step Breakdown:
When you call recur_factorial(5), the function calls itself repeatedly, decreasing n each time:
1. r_factorial(5): Calls r_factorial(4), waiting for its result.
2. r_factorial(4): Calls r_factorial(3), waiting for its result.
3. r_factorial(3): Calls r_factorial(2), waiting for its result.
4. r_factorial(2): Calls r_factorial(1), waiting for its result.
5. r_factorial(1): Base case reached → returns 1.
Now, as each function returns, it resumes execution from where it left off:
6. r_factorial(2): t = 1 * 2 = 2, returns 2.
7. r_factorial(3): t = 2 * 3 = 6, returns 6.
8. r_factorial(4): t = 6 * 4 = 24, returns 24.
9. r_factorial(5): t = 24 * 5 = 120, returns 120.
Why the Loop "Keeps Working":
The function doesn't loop in the traditional sense (like a for or while loop). Instead, it stacks function calls.
Each function call pauses execution until the smaller subproblem is solved.
Once n == 1 is reached, the function starts returning values back up.
This
is a fundamental principle of recursion: solve the smallest problem
first, then use that result to solve the larger problems.
Example from the Python course:
https://www.youtube.com/watch?v=fW_OS3LGB9Q&t=869s
Comments
Post a Comment