Discussion 4: Recursion

Recursion

Many students find this topic challenging. Everything gets easier with practice. Please help each other learn.

Q1: Swipe

Implement swipe, which prints the digits of argument n, one per line, first backward then forward. The left-most digit is printed only once. Do not use while or for or str. (Use recursion, of course!)

Run in 61A Code

Q2: Skip Factorial

Define the base case for the skip_factorial function, which returns the product of every other positive integer, starting with n.

Run in 61A Code

Q3: Recursive 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. Complete this recursive version of hailstone that prints out the values of the sequence and returns the number of steps.

Run in 61A Code

Extra Questions

The questions below are optional but recommended if you would like some extra practice.

Q4: Is Prime

Implement is_prime that takes an integer n greater than 1. It returns True if n is a prime number and False otherwise. Try following the approach below, but implement it recursively without using a while (or for) statement.

def is_prime(n):
    assert n > 1
    i = 2
    while i < n:
        if n % i == 0:
            return False
        i = i + 1
    return True

You will need to define another "helper" function (a function that exists just to help implement this one). Does it matter whether you define it within is_prime or as a separate function in the global frame? Try to define it to take as few arguments as possible.

Run in 61A Code
Define an inner function that checks whether some integer between i and n evenly divides n. Then you can call it starting with i=2:
def is_prime(n):
    def f(i):
        if n % i == 0:
            return ____
        elif ____:
            return ____
        else:
            return f(____)
    return f(2)