Lab 3: Recursion, Tree Recursion
Due by 11:59pm on Tuesday, July 8.
Starter Files
Download lab03.zip.
Topics
Consult this section if you need a refresher on the material for this lab. It's okay to skip directly to the questions and refer back here should you get stuck.
Let's look at the canonical example, factorial
.
Factorial, denoted with the
!
operator, is defined as:n! = n * (n-1) * ... * 1
For example,
5! = 5 * 4 * 3 * 2 * 1 = 120
The recursive implementation for factorial is as follows:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
We know from its definition that 0! is 1. Since n == 0
is the smallest number we
can compute the factorial of, we use it as our base case.
The recursive step also follows from the definition of factorial, i.e., n! =
n * (n-1)!
.
Recursive functions have three important components:
Base case. You can think of the base case as the case of the simplest function input, or as the stopping condition for the recursion.
In our example,
factorial(0)
is our base case for thefactorial
function.Recursive call on a smaller problem. You can think of this step as calling the function on a smaller problem that our current problem depends on. We assume that a recursive call on this smaller problem will give us the expected result; we call this idea the "recursive leap of faith".
In our example,
factorial(n)
depends on the smaller problem offactorial(n-1)
.Solve the larger problem. In step 2, we found the result of a smaller problem. We want to now use that result to figure out what the result of our current problem should be, which is what we want to return from our current function call.
In our example, we can compute
factorial(n)
by multiplying the result of our smaller problemfactorial(n-1)
(which represents(n-1)!
) byn
(the reasoning being thatn! = n * (n-1)!
).
The next few questions in lab will have you writing recursive functions. Here are some general tips:
- Paradoxically, to write a recursive function, you must assume that the function is fully functional before you finish writing it; this is called the recursive leap of faith.
- Consider how you can solve the current problem using the solution to a simpler version of the problem. The amount of work done in a recursive function can be deceptively little: remember to take the leap of faith and trust the recursion to solve the slightly smaller problem without worrying about how.
- Think about what the answer would be in the simplest possible case(s). These will be your base cases - the stopping points for your recursive calls. Make sure to consider the possibility that you're missing base cases (this is a common way recursive solutions fail).
- It may help to write an iterative version first.
For example, this is the Virahanka-Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, ...
.
Each term is the sum of the previous two terms. This tree-recursive function calculates the n
th Virahanka-Fibonacci number.
def virfib(n):
if n == 0 or n == 1:
return n
return virfib(n - 1) + virfib(n - 2)
Calling virfib(6)
results in a call structure that resembles
an upside-down tree (where f
is virfib
):
Each recursive call f(i)
makes a call to f(i-1)
and a call to f(i-2)
.
Whenever we reach an f(0)
or f(1)
call, we can directly return 0
or 1
without making more recursive calls. These calls are our base cases.
A base case returns an answer without depending on the results of other calls. Once we reach a base case, we can go back and answer the recursive calls that led to the base case.
As we will see, tree recursion is often effective for problems with branching choices. In these problems, you make a recursive call for each branching choice.
Here are some examples of tree-recursive problems:
- Given a list of paid tasks and a limited amount of time, which tasks should you choose to maximize your pay? This is actually a variation of the Knapsack problem, which focuses on finding some optimal combination of items.
- Suppose you are lost in a maze and see several different paths. How do you find your way out? This is an example of path finding, and is tree recursive because at every step, you could have multiple directions to choose from that could lead out of the maze.
- Your dryer costs $2 per cycle and accepts all types of coins. How many different combinations of coins can you create to run the dryer? This is similar to the partitions problem from the textbook.
Required Questions
Getting Started Videos
These videos may provide some helpful direction for tackling the coding problems on this assignment.
To see these videos, you should be logged into your berkeley.edu email.
Recursion
Q1: Double Eights
Write a recursive function that takes in a positive integer n
and determines if its
digits contain two adjacent 8
s (that is, two 8
s right next to each other).
Hint: Start by coming up with a recursive plan: the digits of a number have double eights if either (think of something that is straightforward to check) or double eights appear in the rest of the digits.
Important: Use recursion; the tests will fail if you use any loops (for, while).
def double_eights(n):
"""Returns whether or not n has two digits in row that
are the number 8.
>>> double_eights(1288)
True
>>> double_eights(880)
True
>>> double_eights(538835)
True
>>> double_eights(284682)
False
>>> double_eights(588138)
True
>>> double_eights(78)
False
>>> # ban iteration
>>> from construct_check import check
>>> check(SOURCE_FILE, 'double_eights', ['While', 'For'])
True
"""
"*** YOUR CODE HERE ***"
Use Ok to test your code:
python3 ok -q double_eights
Q2: GCD
The greatest common divisor of two positive integers a
and b
is the
largest integer which evenly divides both numbers (with no remainder).
Euclid, a Greek mathematician in 300 B.C., realized that the greatest
common divisor of a
and b
is one of the following:
- the smaller value if it evenly divides the larger value, or
- the greatest common divisor of the smaller value and the remainder of the larger value divided by the smaller value
In other words, if a
is greater than b
and a
is not divisible by
b
, then
gcd(a, b) = gcd(b, a % b)
Write the gcd
function recursively using Euclid's algorithm.
def gcd(a, b):
"""Returns the greatest common divisor of a and b.
Should be implemented using recursion.
>>> gcd(34, 19)
1
>>> gcd(39, 91)
13
>>> gcd(20, 30)
10
>>> gcd(40, 40)
40
"""
"*** YOUR CODE HERE ***"
Use Ok to test your code:
python3 ok -q gcd
Tree Recursion
Q3: WWPD: Squared Virahanka Fibonacci
Use Ok to test your knowledge with the following "What Would Python Display?" questions:
python3 ok -q squared-virfib-wwpd -u
Hint: If you are stuck, make sure to try drawing out the recursive call tree! This is a challenging problem -- doing so will really help with understanding how tree recursion works. We strongly encourage trying to draw things out before asking for help.
Background: In the Squared Virahanka Fibonacci sequence, each number in the sequence is the square of the sum of the previous two numbers in the sequence. The first 0th and 1st number in the sequence are 0 and 1, respectively. The recursive
virfib_sq
function takes in an argumentn
and returns thenth
number in the Square Virahanka Fibonacci sequence.
>>> def virfib_sq(n):
>>> print(n)
>>> if n <= 1:
>>> return n
>>> return (virfib_sq(n - 1) + virfib_sq(n - 2)) ** 2
>>> r0 = virfib_sq(0)
______0
>>> r1 = virfib_sq(1)
______1
>>> r2 = virfib_sq(2)
______2
1
0
>>> r3 = virfib_sq(3)
______3
2
1
0
1
>>> r3
______4
>>> (r1 + r2) ** 2
______4
>>> r4 = virfib_sq(4)
______4
3
2
1
0
1
2
1
0
>>> r4
______25
Q4: Pascal's Triangle
Pascal's triangle gives the coefficients of a binomial expansion; if you expand the expression (a + b) ** n
,
all coefficients will be found on the n
th row of the triangle, and the coefficient of the i
th term will be at the i
th column.
Here's a part of the Pascal's trangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Every number in Pascal's triangle is defined as the sum of the item above it and the item above and to the left of it. Rows and columns are zero-indexed; that is, the first row is row 0 instead of 1 and the first column is column 0 instead of column 1. For example, the item at row 2, column 1 in Pascal's triangle is 2.
Now, define the procedure pascal(row, column)
which takes a row and a column,
and finds the value of the item at that position in Pascal's triangle.
Note that Pascal's triangle is only defined at certain areas;
use 0
if the item does not exist. For the purposes of this question,
you may also assume that row >= 0
and column >= 0
.
Hint: Pascal's Triangle can be visualized as a grid rather than a geometric, three-sided triangle. With this in mind, how does the position of the value you are trying to find relate to the positions of the two numbers that add up to it? At what coordinates of the "grid" do we find out the value and don't need further calculations? Remember that the positions are 0-indexed!
Here is a visualization of the grid:
def pascal(row, column):
"""Returns the value of the item in Pascal's Triangle
whose position is specified by row and column.
>>> pascal(0, 0) # The top left (the point of the triangle)
1
>>> pascal(0, 5) # Empty entry; outside of Pascal's Triangle
0
>>> pascal(3, 2) # Row 3 (1 3 3 1), Column 2
3
>>> pascal(4, 2) # Row 4 (1 4 6 4 1), Column 2
6
"""
"*** YOUR CODE HERE ***"
Use Ok to test your code:
python3 ok -q pascal
Q5: Insect Combinatorics
Consider an insect in an M by N grid. The insect starts at the
bottom left corner, (1, 1), and wants to end up at the top right
corner, (M, N). The insect is only capable of moving right or
up. Write a function paths
that takes a grid length and width
and returns the number of different paths the insect can take from the
start to the goal. (There is a closed-form solution to this problem,
but try to answer it procedurally using recursion.)
For example, the 2 by 2 grid has a total of two ways for the insect to move from the start to the goal. For the 3 by 3 grid, the insect has 6 diferent paths (only 3 are shown above).
Hint: What happens if we hit the top or rightmost edge?
def paths(m, n):
"""Return the number of paths from one corner of an
M by N grid to the opposite corner.
>>> paths(2, 2)
2
>>> paths(5, 7)
210
>>> paths(117, 1)
1
>>> paths(1, 157)
1
"""
"*** YOUR CODE HERE ***"
Use Ok to test your code:
python3 ok -q paths
Check Your Score Locally
You can locally check your score on each question of this assignment by running
python3 ok --score
This does NOT submit the assignment! When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it.
Submit Assignment
Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment. Lab 00 has detailed instructions. Correctly completing all questions is worth one point for regular section students and two points for mega section students.
If you are in regular section, be sure to fill out your TA's attendance form before you leave section. Attending lab section is worth one point for regular section students.