Here's an example of a recursive function in Python that calculates the factorial of a number:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
In this function, the base case is when n is 0 or 1, in which case the function returns 1. The
recursive case is when n is greater than 1, in which case the function returns n multiplied by the
factorial of n-1. The termination condition is implicit in the base case, where the function stops
calling itself when n is 0 or 1.
Here's a hand-drawn plot illustrating how the factorial function works:
factorial(4)
/ | \
factorial(3) | factorial(2)
/ | \ | / | \
factorial(2) | factorial(1) |factorial(0)
/ | | \
factorial(1) | factorial(0)
/ |
factorial(0)
As you can see, the function calls itself with smaller and smaller inputs, until it reaches the base
case of factorial(0) or factorial(1). At that point, the function returns 1, and the
results propagate back up the call stack, allowing the original call to factorial(4) to return
the final result of 24.
I hope this summary of the key components of recursion, along with the examples, has been
helpful! Let me know if you have any questions or if there's anything else I can do to help.
To begin, it's important to understand what a stack is in the context of recursion. A stack is a
data structure that follows the Last In, First Out (LIFO) principle. This means that the last
element added to the stack is the first one to be removed.