Introduction To Programming in Python
Introduction To Programming in Python
1! = 1
n! = n ∗ (n − 1)!, for n > 1 Mathematical definition:
1! = 1
n! = n ∗ (n − 1)!, for n > 1
For example, to compute 5! we do the following:
5! = 5 ∗ 4! (1)
Here’s a straightforward implementation in Python.
= 5 ∗ (4 ∗ 3!) (2)
def fact ( n ) :
= 5 ∗ (4 ∗ (3 ∗ 2!)) (3) """ Factorial function . """
if n == 1: # base case
= 5 ∗ (4 ∗ (3 ∗ (2 ∗ 1!))) (4) return 1
= 5 ∗ (4 ∗ (3 ∗ (2 ∗ 1))) (5) else :
return n * fact (n -1) # recursive case
= 5 ∗ (4 ∗ (3 ∗ 2)) (6)
= 5 ∗ (4 ∗ 6) (7) This function is recursive because it calls itself.
= 5 ∗ 24 (8) Can you see anything wrong with this? How might you fix it?
= 120 (9)
How to Think about Recursion Factorial Again
def factBad ( n ) :
1 A recursive function must have one or more base return n * factBad ( n - 1 )
cases—calculated directly without a recursive call.
2 It must have one or more recursive calls; without that it’s not def isEven ( n ) :
recursive. if n == 0:
3 Each recursive call must move the computation closer to a return True
base case (usually by making the argument “smaller” in the else :
recursive call). return isEven ( n - 2)
Texas Summer Discovery Slideset 12: 11 Recursion Texas Summer Discovery Slideset 12: 12 Recursion
Recursive Thinking: Some Examples Recursive Thinking: Some Examples
An algorithm that dates from Euclid finds the greatest common
Example: how can you reverse a list L? divisor of two positive integers: