Recursion (answer)
Did you manage to write the recursive factorial
function? I hope so. So now let’s compare answers.
def factorial(n):
if n == 1:
return 1
else:
return (n * factorial(n-1))
And here is a visualisation for a function call factorial(4)
:
- factorial(4)
- 4 * factorial(3)
- 4 * (3 * factorial(2))
- 4 * (3 * (2 * factorial(1)))
- 4 * (3 * (2 * 1))
- 4 * (3 * 2)
- 4 * (6)
- 24
Sometimes it helps to think about recursion in a more abstract or high-level manner, rather than being bogged down by all the details. For example, “factorial(n)
will multiply n
by factorial(n-1)
, and will stop once we reach factorial(1)
. Then 1
will be returned to whoever called it, and everything will multiply accordingly.”
Of course, you can easily write this using a loop (try this if you like).
But there are times when using recursion is more elegant and readable (and perhaps easier to write). Some good examples are when you want to generate a tree or a nested sequence. Recursive functions will help break down complex tasks such as those into simpler sub-problems.