In: Computer Science
Can someone please explain to me why "return 1" in this Python code returns the factorial of a given number? I understand recursion, but I do not understand why factorial(5) returns 120 when it clearly says to return 1.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
ANS:
#factorial function
def factorial(n):
#if n equals 0
if n == 0:
#returns 1
return 1
#if n not equals 0
else:
#returns n * factorial(n-1)
return n * factorial(n - 1)
return 1 is applicable only if n equals 0
otherwise the else block will be executed
Example:
factorial(5) is called
n = 5 and not equals 0
else block is executed
ie., factorial(5) returns 5 * factorial(5 - 1) = 5 *
factorial(4)
now factorial(5) = 5 * factorial(4)
in the else block factorial(4) is called
n = 4 and not equals 0
else block is executed
ie., factorial(4) returns 4 * factorial(4 -1) = 4 *
factorial(3)
now factorial(5) = 5 * 4 * factorial(3)
factorial(3) = 3 * factorial(3 - 1) = 3 *
factorial(2)
now factorial(5) = 5 * 4 * 3 * factorial(2)
factorial(2) = 2 * factorial(2 - 1) = 2 *
factorial(1)
now factorial(5) = 5 * 4 * 3 * 2 * factorial(1)
factorial(1) = 1 * factorial(1 - 1) = 1 *
factorial(0)
now factorial(5) = 5 * 4 * 3 * 2 * 1 *
factorial(0)
factorial(0) is called
n == 0
if block is executed
ie., factorial(0) returns 1
now factorial(5) = 5 * 4 * 3 * 2 * 1 * 1
no more function calls.
ie., factorial(5) returns 5 * 4 * 3 * 2 * 1 * 1
ie., factorial(5) returns 120