This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 6: Recursion

Factorials

face Josiah Wang

Hope you have managed to implement the recursive version of the factorial function! Here is my implementation. If you tried defining it mathematically earlier, this is just a directly implementation of the definition.

1
2
3
4
5
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

And in case this is useful, here is a text-based visualisation for the 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

Like I mentioned earlier, 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, you can think of the problem as follows: “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.” All you need to do is to trust that your recursion will work correctly!