Getting Started
if n > 1:
return n * factorial(n-1)
print("Ending condition met.")
return 1
print(factorial(5))
factorial called with n = 5
factorial called with n = 4
factorial called with n = 3
factorial called with n = 2
factorial called with n = 1
Ending condition met.
120
Note the difference. Instead of checking the ending condition, this version checks
the continuation condition. As long as
n
is greater than
1
, the code will continue
to make recursive calls. Even though this code is shorter than the previous ver-
sion, it’s also less clear because now you must think about what condition will end
the recursion.
Do'stlaringiz bilan baham: |