Lab 3: Recursion

Due at 11:59pm on Friday, 07/05/2019.

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.


By the end of this lab, you should have submitted the lab with python3 ok --submit. You may submit more than once before the deadline; only the final submission will be graded. Check that you have successfully submitted your code on

  • Questions 1-3 must be completed in order to receive credit for this lab. Starter code for these questions is in
  • Questions 4-6 are optional, but highly recommended if you have the time. Starter code for these questions is in the file.


Consult this section if you are unfamiliar with the material for this lab. It's okay to skip directly to the questions and refer back here if 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

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. So we choose n == 0 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 the iterative version first.

Required Questions

Q1: Skip Add

Write a function skip_add that takes a single argument n and computes the sum of every other integer between 0 and n. Assume n is non-negative.

def skip_add(n):
    """ Takes a number x and returns x + x-2 + x-4 + x-6 + ... + 0.

    >>> skip_add(5)  # 5 + 3 + 1 + 0
    >>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0
    >>> # Do not use while/for loops!
    >>> from construct_check import check
    >>> check('', 'skip_add',
    ...       ['While', 'For'])
"*** YOUR CODE HERE ***"
if n <= 0: return 0 return n + skip_add(n - 2)

Use Ok to test your code:

python3 ok -q skip_add

Q2: Hailstone

Recall the hailstone function from homework 1. First, pick a positive integer n as the start. If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. Repeat this process until n is 1. Write a recursive version of hailstone that prints out the values of the sequence and returns the number of steps.

Hint: When taking the recursive leap of faith, consider both the return value and side effect of this function.

this_file = __file__

def hailstone(n):
    """Print out the hailstone sequence starting at n, and return the
    number of elements in the sequence.

    >>> a = hailstone(10)
    >>> a
    >>> # Do not use while/for loops!
    >>> from construct_check import check
    >>> check(this_file, 'hailstone',
    ...       ['While', 'For'])
"*** YOUR CODE HERE ***"
print(n) if n == 1: return 1 elif n % 2 == 0: return 1 + hailstone(n // 2) else: return 1 + hailstone(3 * n + 1) # Alternate solution with helper function def hailstone2(n): def hail_helper(n, count): print(n) if n == 1: return count else: if n % 2 == 0: return hail_helper(n // 2, count + 1) else: return hail_helper(3 * n + 1, count + 1) return hail_helper(n, 1) # Video walkthrough:

Use Ok to test your code:

python3 ok -q hailstone

Q3: Summation

Now, 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 of the results.

def summation(n, term):

    """Return the sum of the first n terms in the sequence defined by term.
    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
    >>> check(this_file, 'summation',
    ...       ['While', 'For'])
    assert n >= 1
"*** YOUR CODE HERE ***"
if n == 1: return term(n) else: return term(n) + summation(n - 1, term) # Base case: only one item to sum, so we return that item. # Recursive call: returns the result of summing the numbers up to n-1 using # term. All that's missing is term applied to the current value n.

Use Ok to test your code:

python3 ok -q summation

Optional Questions

Note: The following questions are in

More Recursion Practice

Q4: Is Prime

Write a function is_prime that takes a single argument n and returns True if n is a prime number and False otherwise. Assume n > 1. We implemented this in Discussion 1 iteratively, now time to do it recursively!

Hint: You will need a helper function! Remember helper functions are useful if you need to keep track of more variables than the given parameters, or if you need to change the value of the input.

def is_prime(n):
    """Returns True if n is a prime number and False otherwise.

    >>> is_prime(2)
    >>> is_prime(16)
    >>> is_prime(521)
"*** YOUR CODE HERE ***"
def helper(i): if i > (n ** 0.5): # Could replace with i == n return True elif n % i == 0: return False return helper(i + 1) return helper(2) # Video Walkthrough:

Use Ok to test your code:

python3 ok -q is_prime


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)
    >>> gcd(39, 91)
    >>> gcd(20, 30)
    >>> gcd(40, 40)
"*** YOUR CODE HERE ***"
a, b = max(a, b), min(a, b) if a % b == 0: return b else: return gcd(b, a % b) # Iterative solution, if you're curious def gcd_iter(a, b): """Returns the greatest common divisor of a and b, using iteration. >>> gcd_iter(34, 19) 1 >>> gcd_iter(39, 91) 13 >>> gcd_iter(20, 30) 10 >>> gcd_iter(40, 40) 40 """ if a < b: return gcd_iter(b, a) while a > b and not a % b == 0: a, b = b, a % b return b # Video Walkthrough:

Use Ok to test your code:

python3 ok -q gcd

Q6: Ten-pairs

Write a function that takes a positive integer n and returns the number of ten-pairs it contains. A ten-pair is a pair of digits within n that sums to 10. Do not use any assignment statements.

The number 7,823,952 has 3 ten-pairs. The first and fourth digits sum to 7+3=10, the second and third digits sum to 8+2=10, and the second and last digit sum to 8+2=10. Note that a digit can be part of more than one ten-pair.

Hint: Use a helper function to calculate how many times a digit appears in n.

def ten_pairs(n):
    """Return the number of ten-pairs within positive integer n.

    >>> ten_pairs(7823952)
    >>> ten_pairs(55055)
    >>> ten_pairs(9641469)
"*** YOUR CODE HERE ***"
if n < 10: return 0 else: return ten_pairs(n//10) + count_digit(n//10, 10 - n%10) def count_digit(n, digit): """Return how many times digit appears in n. >>> count_digit(55055, 5) 4 """ if n == 0: return 0 else: if n%10 == digit: return count_digit(n//10, digit) + 1 else: return count_digit(n//10, digit)

Use Ok to test your code:

python3 ok -q ten_pairs