Lab 3 Solutions

Solution Files


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. Recursive functions have three important components:

  1. Base case(s), the simplest possible form of the problem you're trying to solve.
  2. Recursive case(s), where the function calls itself with a simpler argument as part of the computation.
  3. Using the recursive calls to solve the full problem.

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)!.

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.

A classic example of a tree recursion function is finding the nth Fibonacci number:

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

Calling fib(6) results in the following call structure (where f is fib):

Fibonacci Tree

Each f(i) node represents a recursive call to fib. Each recursive call makes another two recursive calls. f(0) and f(1) do not make any recursive calls because they are the base cases of the function. Because of these base cases, we are able to terminate the recursion and beginning accumulating the values.

Generally, tree recursion is effective when you want to explore multiple possibilities or choices at a single step. In these types of problems, you make a recursive call for each choice or for a group of choices. Here are some examples:

  • 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 different 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

What Would Python Display?

Q1: WWPD: Recursion

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

python3 ok -q recursion-wwpd -u

For all WWPD questions, type Function if you believe the answer is <function...>, Error if it errors, Infinite if there is an infinite loop or infinite recursion, and Nothing if nothing is displayed.

>>> def f(a, b):
...     if a > b:
...     	return f(a - 3, 2 * b)
...     elif a < b:
...		return f(b // 2, a)
...     else:
...     	return b
>>> f(2, 2)
>>> f(7, 4)
>>> f(2, 28)
>>> f(-1, -3)

Q2: WWPD: Journey to the Center of the Earth

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

python3 ok -q sr-wwpd -u

For all WWPD questions, type Function if you believe the answer is <function...>, Error if it errors, and Nothing if nothing is displayed.

>>> def crust():
...     print("70km")
...     def mantle():
...          print("2900km")
...          def core():
...               print("5300km")
...               return mantle()
...          return core
...     return mantle
>>> drill = crust
>>> drill = drill()
>>> drill = drill()
>>> drill = drill()
5300km 2900km
>>> drill()
5300km 2900km Function

Coding Practice

Q3: Pascal's Triangle

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 that is directly to the upper left of it. Use 0 if the entry is empty. Define the procedure pascal(row, column) which takes a row and a column, and finds the value at that position in the triangle. Rows and columns are zero-indexed; that is, the first row is row 0 instead of 1.

def pascal(row, column):
    """Returns a number corresponding to the value at that location
    in Pascal's Triangle.
    >>> pascal(0, 0)
    >>> pascal(0, 5)	# Empty entry; outside of Pascal's Triangle
    >>> pascal(3, 2)	# Row 4 (1 3 3 1), 3rd entry
if column == 0: return 1 elif row == 0: return 0 else: return pascal(row - 1, column) + pascal(row - 1, column - 1)

Use Ok to test your code:

python3 ok -q pascal

Q4: Repeated, repeated

In Homework 2 you encountered the repeated function, which takes arguments f and n and returns a function equivalent to the nth repeated application of f. This time, we want to write repeated recursively. You'll want to use compose1, given below for your convenience:

def compose1(f, g):
    """"Return a function h, such that h(x) = f(g(x))."""
    def h(x):
        return f(g(x))
    return h
def repeated(f, n):
    """Return the function that computes the nth application of func (recursively!).

    >>> add_three = repeated(lambda x: x + 1, 3)
    >>> add_three(5)
    >>> square = lambda x: x ** 2
    >>> repeated(square, 2)(5) # square(square(5))
    >>> repeated(square, 4)(5) # square(square(square(square(5))))
    >>> repeated(square, 0)(5)
    >>> from construct_check import check
    >>> # ban iteration
    >>> check(HW_SOURCE_FILE, 'repeated',
    ...       ['For', 'While'])
if n == 0: return lambda x: x #Identity return compose1(f, repeated(f, n - 1))

Use Ok to test your code:

python3 ok -q repeated

Q5: Num eights

Write a recursive function num_eights that takes a positive integer x and returns the number of times the digit 8 appears in x. Use recursion - the tests will fail if you use any assignment statements.

def num_eights(x):
    """Returns the number of times 8 appears as a digit of x.

    >>> num_eights(3)
    >>> num_eights(8)
    >>> num_eights(88888888)
    >>> num_eights(2638)
    >>> num_eights(86380)
    >>> num_eights(12345)
    >>> from construct_check import check
    >>> # ban all assignment statements
    >>> check(HW_SOURCE_FILE, 'num_eights',
    ...       ['Assign', 'AugAssign'])
if x % 10 == 8: return 1 + num_eights(x // 10) elif x < 10: return 0 else: return num_eights(x // 10)

Watch the hints video below for somewhere to start:

Use Ok to test your code:

python3 ok -q num_eights

The equivalent iterative version of this problem might look something like this:

total = 0
while x > 0:
    if x % 10 == 8:
        total = total + 1
    x = x // 10
return total

The main idea is that we check each digit for a eight. The recursive solution is similar, except that you depend on the recursive call to count the occurences of eight in the rest of the number. Then, you add that to the number of eights you see in the current digit.

Q6: Ping-pong

The ping-pong sequence counts up starting from 1 and is always either counting up or counting down. At element k, the direction switches if k is a multiple of 8 or contains the digit 8. The first 30 elements of the ping-pong sequence are listed below, with direction swaps marked using brackets at the 8th, 16th, 18th, 24th, and 28th elements:

Index 1 2 3 4 5 6 7 [8] 9 10 11 12 13 14 15 [16] 17 [18] 19 20 21 22 23
PingPong Value 1 2 3 4 5 6 7 [8] 7 6 5 4 3 2 1 [0] 1 [2] 1 0 -1 -2 -3
Index (cont.) [24] 25 26 27 [28] 29 30
PingPong Value [-4] -3 -2 -1 [0] -1 -2

Implement a function pingpong that returns the nth element of the ping-pong sequence without using any assignment statements.

You may use the function num_eights, which you defined in the previous question.

Use recursion - the tests will fail if you use any assignment statements.

Hint: If you're stuck, first try implementing pingpong using assignment statements and a while statement. Then, to convert this into a recursive solution, write a helper function that has a parameter for each variable that changes values in the body of the while loop.

def pingpong(n):
    """Return the nth element of the ping-pong sequence.

    >>> pingpong(8)
    >>> pingpong(10)
    >>> pingpong(15)
    >>> pingpong(21)
    >>> pingpong(22)
    >>> pingpong(30)
    >>> pingpong(68)
    >>> pingpong(69)
    >>> pingpong(80)
    >>> pingpong(81)
    >>> pingpong(82)
    >>> pingpong(100)
    >>> from construct_check import check
    >>> # ban assignment statements
    >>> check(HW_SOURCE_FILE, 'pingpong', ['Assign', 'AugAssign'])
def helper(result, i, step): if i == n: return result elif i % 8 == 0 or num_eights(i) > 0: return helper(result - step, i + 1, -step) else: return helper(result + step, i + 1, step) return helper(1, 1, 1) # Alternate solution 1 def pingpong_next(x, i, step): if i == n: return x return pingpong_next(x + step, i + 1, next_dir(step, i+1)) def next_dir(step, i): if i % 8 == 0 or num_eights(i) > 0: return -step return step # Alternate solution 2 def pingpong_alt(n): if n <= 8: return n return direction(n) + pingpong_alt(n-1) def direction(n): if n < 8: return 1 if (n-1) % 8 == 0 or num_eights(n-1) > 0: return -1 * direction(n-1) return direction(n-1)

Watch the hints video below for somewhere to start:

Use Ok to test your code:

python3 ok -q pingpong

This is a fairly involved recursion problem, which we will first solve through iteration and then convert to a recursive solution.

Note that at any given point in the sequence, we need to keep track of the current value of the sequence (this is the value that might be output) as well as the current index of the sequence (how many items we have seen so far, not actually output).

For example, 14th element has value 0, but it's the 14th index in the sequence. We will refer to the value as x and the index as i. An iterative solution may look something like this:

def pingpong(n):
    i = 1
    x = 1
    while i < n:
        x += 1
        i += 1
    return x

Hopefully, it is clear to you that this has a big problem. This doesn't account for changes in directions at all! It will work for the first eight values of the sequence, but then fail after that. To fix this, we can add in a check for direction, and then also keep track of the current direction to make our lives a bit easier (it's possible to compute the direction from scratch at each step, see the direction function in the alternate solution).

def pingpong(n):
    i = 1
    x = 1
    is_up = True
    while i < n:
        is_up = next_dir(...)
        if is_up:
            x += 1
            x -= 1
        i += 1
    return x

All that's left to do is to write the next_dir function, which will take in the current direction and index and then tell us what direction to go in next (which could be the same direction):

def next_dir(is_up, i):
    if i % 8 == 0 or num_eights(i) > 0:
        return not is_up
    return is_up

There's a tiny optimization we can make here. Instead of calculating an increment based on the value of is_up, we can make it directly store the direction of change into the variable (next_dir is also updated, see the solution for the new version):

def pingpong(n):
    i = 1
    x = 1
    step = 1
    while i < n:
        step = next_dir(step, i)
        x += step
        i += 1
    return x

This will work, but it uses assignment. To convert it to an equivalent recursive version without assignment, make each local variable into a parameter of a new helper function, and then add an appropriate base case. Lastly, we seed the helper function with appropriate starting values by calling it with the values we had in the iterative version.

You should be able to convince yourself that the version of pingpong in the solutions has the same logic as the iterative version of pingpong above.

Video walkthrough: