Week 11 - Recursion
Week 11 - Recursion
Recursion
Topics: recursion.
Drills
Infinity
Examine the snippet of code below.
1 def spam(n):
2 # if n == 0:
3 # return n
4 return spam(n-1)
5
6 ham = spam(3) # what is the value of `ham`?
Factorial
The factorial of a non-negative integer is denoted by , and can be defined as:
1 factorial(4) # 24
2 factorial(3) # 6
3 factorial(2) # 2
4 factorial(1) # 1
5 factorial(0) # 1
6 factorial(1000) # what happens here?
Problems
Binomial
Write a function binomial(n, k) that returns the binomial coefficient " choose ", defined as:
Hint: Use your factorial function. Your binomial function should not be recursive!
Fibonacci
Write a recursive function fibonacci(n) that returns the n th Fibonacci number.
1 fibonacci(8) # 21
2 fibonacci(7) # 13
3 fibonacci(6) # 8
4 fibonacci(0) # 0
Hint: What are the base cases? (There are two.) What is the recurrence relation?
Hailstones redux
Recall the Hailstones problem (in the Week 3 tute):
Repeat the above process indefinitely. The Collatz conjecture says that you will always eventually reach
the number 1 .
For example, starting with the number 6 , we get the numbers 6, 3, 10, 5, 16, 8, 4, 2, 1 , known
as the hailstone sequence or hailstone numbers.
Write a recursive function hailstones(n) that returns the hailstone sequence starting at the integer n .
Iteration
Write an iterative function to solve each of the Factorial, Fibonacci and Hailstones problems.
Note: You should probably attempt an iterative Fibonacci solution last—it is a bit tricky!
What are the advantages and disadvantages of a recursive implementation over an iterative one?
Extensions
Twenty Four
Have a look at the Twenty Four challenge on ed. Although it isn't obvious, this problem has a very nice
recursive solution.
Recall that the base case is usually the smallest or simplest instance of a problem.
Think about what the recurrence relation might be.
How can the 24 problem be "reduced", until it reaches the base case?
If you've figured out the recursive solution, go ahead and implement it!
Hint 1: What numbers are mentioned in the challenge description? Could these numbers be made smaller?
Hint 2: Ironically, the recursive solution becomes more obvious if the challenge is "generalised".
Towers of Hanoi
The Towers of Hanoi is a mathematical puzzle, consisting of rods , and , and discs of different sizes.
Initially, all discs are placed on the leftmost rod , with the largest disc at the bottom and the smallest disc
at the top.
The objective is to move all the discs to another rod ( or ), while adhering to these rules:
Write a recursive function that prints all the steps to move discs to another rod.