Homework 1 Solutions

Solution Files

You can find the solutions in hw01.py.

Required Questions

Functions & Control

Q1: A Plus Abs B

Python's operator module contains two-argument functions such as add and sub for Python's built-in arithmetic operators. For example, add(2, 3) evalutes to 5, just like the expression 2 + 3.

Fill in the blanks in the following function to add a to the absolute value of b, without calling the abs function. You may not modify any of the provided code other than the two blanks.

def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    >>> a_plus_abs_b(-1, 4)
    3
    >>> a_plus_abs_b(-1, -4)
    3
    """
    if b < 0:
f = sub
else:
f = add
return f(a, b)

Use Ok to test your code:

python3 ok -q a_plus_abs_b

Use Ok to run the local syntax checker (which checks that you didn't modify any of the provided code other than the two blanks):

python3 ok -q a_plus_abs_b_syntax_check

If b is positive, we add the numbers together. If b is negative, we subtract the numbers. Therefore, we choose the operator add or sub based on the sign of b.

Q2: Hailstone

Douglas Hofstadter's Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle.

  1. Pick a positive integer n as the start.
  2. If n is even, divide it by 2.
  3. If n is odd, multiply it by 3 and add 1.
  4. Continue this process until n is 1.

The number n will travel up and down but eventually end at 1 (at least for all numbers that have ever been tried—nobody has ever proved that the sequence will terminate). Analogously, a hailstone travels up and down in the atmosphere before eventually landing on earth.

This sequence of values of n is often called a Hailstone sequence. Write a function that takes a single argument with formal parameter name n, prints out the hailstone sequence starting at n, and returns the number of steps in the sequence:

def hailstone(n):
    """Print the hailstone sequence starting at n and return its
    length.

    >>> a = hailstone(10)
    10
    5
    16
    8
    4
    2
    1
    >>> a
    7
    >>> b = hailstone(1)
    1
    >>> b
    1
    """
length = 1 while n != 1: print(n) if n % 2 == 0: n = n // 2 # Integer division prevents "1.0" output else: n = 3 * n + 1 length = length + 1 print(n) # n is now 1 return length

Hailstone sequences can get quite long! Try 27. What's the longest you can find?

Note that if n == 1 initially, then the sequence is one step long.
Hint: If you see 4.0 but want just 4, try using floor division // instead of regular division /.

Use Ok to test your code:

python3 ok -q hailstone

Curious about hailstone sequences? Take a look at this article:

  • In 2019, there was a major development in understanding how the hailstone conjecture works for most numbers!

We keep track of the current length of the hailstone sequence and the current value of the hailstone sequence. From there, we loop until we hit the end of the sequence, updating the length in each step.

Note: we need to do floor division // to remove decimals.

Higher-Order Functions

Q3: Product

Write a function called product that returns the product of the first n terms of a sequence. Specifically, product takes in an integer n and term, a single-argument function that determines a sequence (That is, term(i) gives the ith term of the sequence). product(n, term) should return term(1) * ... * term(n).

def product(n, term):
    """Return the product of the first n terms in a sequence.

    n: a positive integer
    term: a function that takes an index as input and produces a term

    >>> product(3, identity)  # 1 * 2 * 3
    6
    >>> product(5, identity)  # 1 * 2 * 3 * 4 * 5
    120
    >>> product(3, square)    # 1^2 * 2^2 * 3^2
    36
    >>> product(5, square)    # 1^2 * 2^2 * 3^2 * 4^2 * 5^2
    14400
    >>> product(3, increment) # (1+1) * (2+1) * (3+1)
    24
    >>> product(3, triple)    # 1*3 * 2*3 * 3*3
    162
    """
prod, k = 1, 1 while k <= n: prod, k = term(k) * prod, k + 1 return prod

Use Ok to test your code:

python3 ok -q product

The prod variable is used to keep track of the product so far. We start with prod = 1 since we will be multiplying, and anything multiplied by 1 is itself. We then initialize the counter variable k to use in the while loop to ensures that we get through all values 1 through k.

Q4: Make Repeater

Implement the function make_repeater which takes a one-argument function f and a positive integer n. It returns a one-argument function so that make_repeater(f, n)(x) returns the value of f(f(...f(x)...)), in which f is applied n times to x. For example, make_repeater(square, 3)(5) squares 5 three times and returns 390625, just like square(square(square(5))).

def make_repeater(f, n):
    """Returns the function that computes the nth application of f.

    >>> add_three = make_repeater(increment, 3)
    >>> add_three(5)
    8
    >>> make_repeater(triple, 5)(1) # 3 * (3 * (3 * (3 * (3 * 1))))
    243
    >>> make_repeater(square, 2)(5) # square(square(5))
    625
    >>> make_repeater(square, 3)(5) # square(square(square(5)))
    390625
    """
def repeater(x): k = 0 while k < n: x, k = f(x), k + 1 return x return repeater

Use Ok to test your code:

python3 ok -q make_repeater

There are many correct ways to implement make_repeater. This solution repeatedly applies h.

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.

Submit Assignment

Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment. Lab 00 has detailed instructions.

Optional Questions

Q5: Largest Factor

Write a function that takes an integer n that is greater than 1 and returns the largest integer that is smaller than n and evenly divides n.

def largest_factor(n):
    """Return the largest factor of n that is smaller than n.

    >>> largest_factor(15) # factors are 1, 3, 5
    5
    >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
    40
    >>> largest_factor(13) # factors are 1, 13
    1
    """
factor = n - 1 while factor > 0: if n % factor == 0: return factor factor -= 1

Hint: To check if b evenly divides a, use the expression a % b == 0, which can be read as, "the remainder when dividing a by b is 0."

Use Ok to test your code:

python3 ok -q largest_factor

Iterating from n-1 to 1, we return the first integer that evenly divides n. This is guaranteed to be the largest factor of n.

Q6: Accumulate

Let's take a look at how product is an instance of a more general function called accumulate, which we would like to implement:

def accumulate(fuse, start, n, term):
    """Return the result of fusing together the first n terms in a sequence 
    and start.  The terms to be fused are term(1), term(2), ..., term(n). 
    The function fuse is a two-argument commutative & associative function.

    >>> accumulate(add, 0, 5, identity)  # 0 + 1 + 2 + 3 + 4 + 5
    15
    >>> accumulate(add, 11, 5, identity) # 11 + 1 + 2 + 3 + 4 + 5
    26
    >>> accumulate(add, 11, 0, identity) # 11 (fuse is never used)
    11
    >>> accumulate(add, 11, 3, square)   # 11 + 1^2 + 2^2 + 3^2
    25
    >>> accumulate(mul, 2, 3, square)    # 2 * 1^2 * 2^2 * 3^2
    72
    >>> # 2 + (1^2 + 1) + (2^2 + 1) + (3^2 + 1)
    >>> accumulate(lambda x, y: x + y + 1, 2, 3, square)
    19
    """
total, k = start, 1 while k <= n: total, k = fuse(total, term(k)), k + 1 return total # Alternative solution def accumulate_reverse(fuse, start, n, term): total, k = start, n while k >= 1: total, k = fuse(total, term(k)), k - 1 return total

accumulate has the following parameters:

  • fuse: a two-argument function that specifies how the current term is fused with the previously accumulated terms
  • start: value at which to start the accumulation
  • n: a non-negative integer indicating the number of terms to fuse
  • term: a single-argument function; term(i) is the ith term of the sequence

Implement accumulate, which fuses the first n terms of the sequence defined by term with the start value using the fuse function.

For example, the result of accumulate(add, 11, 3, square) is

add(11,  add(square(1), add(square(2),  square(3)))) =
    11 +     square(1) +    square(2) + square(3)    =
    11 +     1         +    4         + 9            = 25

Assume that fuse is commutative, fuse(a, b) == fuse(b, a), and associative, fuse(fuse(a, b), c) == fuse(a, fuse(b, c)).

Use Ok to test your code:

python3 ok -q accumulate

Then, implement summation and product as one-line calls to accumulate.

Important: Both summation_using_accumulate and product_using_accumulate should be implemented with a single line of code starting with return.

def summation_using_accumulate(n, term):
    """Returns the sum: term(1) + ... + term(n), using accumulate.

    >>> summation_using_accumulate(5, square) # square(1) + square(2) + ... + square(4) + square(5)
    55
    >>> summation_using_accumulate(5, triple) # triple(1) + triple(2) + ... + triple(4) + triple(5)
    45
    >>> # This test checks that the body of the function is just a return statement.
    >>> import inspect, ast
    >>> [type(x).__name__ for x in ast.parse(inspect.getsource(summation_using_accumulate)).body[0].body]
    ['Expr', 'Return']
    """
return accumulate(add, 0, n, term)
def product_using_accumulate(n, term): """Returns the product: term(1) * ... * term(n), using accumulate. >>> product_using_accumulate(4, square) # square(1) * square(2) * square(3) * square() 576 >>> product_using_accumulate(6, triple) # triple(1) * triple(2) * ... * triple(5) * triple(6) 524880 >>> # This test checks that the body of the function is just a return statement. >>> import inspect, ast >>> [type(x).__name__ for x in ast.parse(inspect.getsource(product_using_accumulate)).body[0].body] ['Expr', 'Return'] """
return accumulate(mul, 1, n, term)

Use Ok to test your code:

python3 ok -q summation_using_accumulate
python3 ok -q product_using_accumulate

We want to abstract the logic of product and summation into accumulate. The differences between product and summation are:

  • How to fuse terms. For product, we fuse via * (mul). For summation, we fuse via + (add).
  • The starting value. For product, we want to start off with 1 since starting with 0 means that our result (via multiplying with the start) will always be 0. For summation, we want to start off with 0.