Recursion: Python Programming, 3/e 1
Recursion: Python Programming, 3/e 1
Or n ! = ì 1 if n = 0
n
í
în(n - 1)! otherwise
n This definition says that 0! is 1, while
the factorial of any other number is that
number times the factorial of one less
than that number.
curr = 1
prev = 1
for i in range(n-2):
curr, prev = curr+prev, curr
return curr
n Note the use of simultaneous assignment to
calculate the new values of curr and prev.
n The loop executes only n-2 times since the
first two values have already been
“determined”.
Python Programming, 3/e 29
Recursion vs. Iteration
n The Fibonacci sequence also has a recursive
definition:
ì 1 if n < 3
fib(n) = í
î fib(n - 1) + fib(n - 2) otherwise
n This recursive definition can be directly
turned into a recursive function!
n def fib(n):
if n < 3:
return 1
else:
return fib(n-1)+fib(n-2)