Lab 3 - Recursion

Instructions: https://inst.eecs.berkeley.edu/~cs61a/su19/lab/lab03/arrow-up-right

Solution: https://github.com/tomthestrom/cs61a/blob/master/lab/lab03/lab03.pyarrow-up-right

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
    9
    >>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0
    30
    >>> # Do not use while/for loops!
    >>> from construct_check import check
    >>> check('lab03.py', 'skip_add',
    ...       ['While', 'For'])
    True
    """
    "*** YOUR CODE HERE ***"

Q1: Solution

Q2: Hailstone

Recall the hailstone function from homework 1arrow-up-right. 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.

Q2: Solution

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.

Q3: Solution

Last updated