Lab 4: Recursion, Tree Recursion, Python Lists

Due by 11:59pm on Wednesday, February 15.

Starter Files

Download Inside the archive, you will find starter files for the questions in this lab, along with a copy of the Ok autograder.


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.


A recursive function is a function that calls itself in its body, either directly or indirectly.

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:

  1. 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 the factorial function.

  2. 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 of factorial(n-1).

  3. 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 problem factorial(n-1) (which represents (n-1)!) by n (the reasoning being that n! = 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.

Tree Recursion

A tree recursive function is a recursive function that makes more than one call to itself, resulting in a tree-like series of calls.

For example, let's say we want to recursively calculate the nth Virahanka-Fibonacci number, defined as:

def virfib(n):
    if n == 0 or n == 1:
        return n
    return virfib(n - 1) + virfib(n - 2)

Calling virfib(6) results in the following call structure that looks like an upside-down tree (where f is virfib):

Virahanka-Fibonacci Tree

Each f(i) node represents a recursive call to virfib. Each recursive call f(i) makes another two recursive calls, which are to f(i-1) and f(i-2). Whenever we reach a f(0) or f(1) node, we can directly return 0 or 1 rather than making more recursive calls, since these are our base cases.

In other words, base cases have the information needed to return an answer directly, without depending upon results from other recursive calls. Once we've reached a base case, we can then begin returning back from the recursive calls that led us to the base case in the first place.

Generally, tree recursion can be effective for problems where there are multiple possibilities or choices at a current state. In these types of problems, you make a recursive call for each choice or for a group of choices.


A list is a data structure that can store multiple elements. Each element can be of any type, even a list itself. We write a list as a comma-separated list of expressions in square brackets:

>>> list_of_ints = [1, 2, 3, 4]
>>> list_of_bools = [True, True, False, False]
>>> nested_lists = [1, [2, 3], [4, [5]]]

Each element in the list has an index, with the index of the first element starting at 0. We say that lists are therefore "zero-indexed."

With list indexing, we can specify the index of the element we want to retrieve. A negative index represents starting from the end of the list, so the negative index -i is equivalent to the positive index len(lst)-i.

>>> lst = [6, 5, 4, 3, 2, 1, 0]
>>> lst[0]
>>> lst[3]
>>> lst[-1] # Same as lst[6]

List Slicing

To create a copy of part or all of a list, we can use list slicing. The syntax to slice a list lst is: lst[<start index>:<end index>:<step size>].

This expression evaluates to a new list containing the elements of lst:

  • Starting at and including the element at <start index>.
  • Up to but not including the element at <end index>.
  • With <step size> as the difference between indices of elements to include.

If the start, end, or step size are not explicitly specified, Python has default values for them. A negative step size indicates that we are stepping backwards through a list when including elements.

>>> lst[:3]   # Start index defaults to 0
[6, 5, 4]
>>> lst[3:]   # End index defaults to len(lst)
[3, 2, 1, 0]
>>> lst[::-1]   # Make a reversed copy of the entire list
[0, 1, 2, 3, 4, 5, 6]
>>> lst[::2]  # Skip every other; step size defaults to 1 otherwise
[6, 4, 2, 0]

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 email.

YouTube link

Recursion/Tree Recursion

Q1: 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 from your TA/AIs.

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 argument n and returns the nth 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)
>>> r1 = virfib_sq(1)
>>> r2 = virfib_sq(2)
2 1 0
>>> r3 = virfib_sq(3)
3 2 1 0 1
>>> r3
>>> (r1 + r2) ** 2
>>> r4 = virfib_sq(4)
4 3 2 1 0 1 2 1 0
>>> r4

Q2: Summation

Write a recursive implementation of summation, which takes a positive integer n and a function term. It applies term to every number from 1 to n including n and returns the sum.

Important: Use recursion; the tests will fail if you use any loops (for, while).

def summation(n, term):
    """Return the sum of numbers 1 through n (including n) wíth term applied to each number.
    Implement using recursion!

    >>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
    >>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
    >>> summation(5, lambda x: 2**x) # 2^1 + 2^2 + 2^3 + 2^4 + 2^5
    >>> # Do not use while/for loops!
    >>> from construct_check import check
    >>> # ban iteration
    >>> check(HW_SOURCE_FILE, 'summation',
    ...       ['While', 'For'])
    assert n >= 1
    "*** YOUR CODE HERE ***"

Use Ok to test your code:

python3 ok -q summation

Q3: 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)
    >>> paths(5, 7)
    >>> paths(117, 1)
    >>> paths(1, 157)
    "*** YOUR CODE HERE ***"

Use Ok to test your code:

python3 ok -q paths


Q4: WWPD: Lists

Use Ok to test your knowledge with the following "What Would Python Display?" questions:

python3 ok -q lists-wwpd -u

Predict what Python will display when you type the following into the interpreter. Then try it to check your answers.

>>> s = [7//3, 5, [4, 0, 1], 2]
>>> s[0]
>>> s[2]
[4, 0, 1]
>>> s[-1]
>>> len(s)
>>> 4 in s
>>> 4 in s[2]
>>> s + [3 + 2, 9]
[2, 5, [4, 0, 1], 2, 5, 9]
>>> s[2] * 2
[4, 0, 1, 4, 0, 1]
>>> x = [1, 2, 3, 4] >>> x[1:3]
[2, 3]
>>> x[:2]
[1, 2]
>>> x[1:]
[2, 3, 4]
>>> x[-2:3]
>>> x[-2:4]
[3, 4]
>>> x[0:4:2]
[1, 3]
>>> x[::-1]
[4, 3, 2, 1]

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.


Make sure to submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment. For a refresher on how to do this, refer to Lab 00.

Optional Questions

These questions are optional, but you must complete them in order to be checked off before the end of the lab period. They are also useful practice!


Q5: 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 nth row of the triangle, and the coefficient of the ith term will be at the ith column.

Here's a part of the Pascal's trangle:

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.

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)
    >>> pascal(0, 5)	# Empty entry; outside of Pascal's Triangle
    >>> pascal(3, 2)	# Row 3 (1 3 3 1), Column 2
    >>> pascal(4, 2)     # Row 4 (1 4 6 4 1), Column 2
    "*** YOUR CODE HERE ***"

Use Ok to test your code:

python3 ok -q pascal

Q6: Double Eights

Write a recursive function that takes in a number n and determines if the digits contain two adjacent 8s. You can assume that n is at least a two-digit number. You may have already done this problem iteratively as an Extra Practice problem in Lab 1.

Hint: Remember what tools you can use in order to isolate digits of a number. If you have trouble figuring out how to implement the recursion, try first finding an iterative solution, and think about how you might be able to turn any loops in recursion.

def double_eights(n):
    """ Returns whether or not n has two digits in row that
    are the number 8. Assume n has at least two digits in it.

    >>> double_eights(1288)
    >>> double_eights(880)
    >>> double_eights(538835)
    >>> double_eights(284682)
    >>> double_eights(588138)
    >>> double_eights(78)
    >>> from construct_check import check
    >>> # ban iteration
    >>> check(HW_SOURCE_FILE, 'double_eights', ['While', 'For'])
    "*** YOUR CODE HERE ***"

Use Ok to test your code:

python3 ok -q double_eights