# Homework 2

*Due by 11:59pm on Tuesday, 2/16*

## Instructions

Download hw02.zip. Inside the archive, you will find a file called hw02.py, along with a copy of the OK autograder.

**Submission:** When you are done, submit with ```
python3 ok
--submit
```

. You may submit more than once before the deadline; only the
final submission will be scored. See Lab 0 for instructions on submitting
assignments.

**Using OK:** If you have any questions about using OK, please
refer to this guide.

**Readings:** You might find the following references
useful:

## Required questions

Several doctests use the `construct_check`

module, which defines a
function `check`

. For example, a call such as

`check("foo.py", "func1", ["While", "For", "Recursion"])`

checks that the function `func1`

in file `foo.py`

does *not* contain
any `while`

or `for`

constructs, and is not an overtly recursive function (i.e.,
one in which a function contains a call to itself by name.)

Several doctests refer to these one-argument functions:

```
def square(x):
return x * x
def triple(x):
return 3 * x
def identity(x):
return x
def increment(x):
return x + 1
```

### Question 1: Product

The `summation(term, n)`

function from lecture adds up `term(1) + ... + term(n)`

Write a similar `product(n, term)`

function that returns ```
term(1) * ... *
term(n)
```

. Show how to define the
factorial function in terms of
`product`

. *Hint*: try using the `identity`

function for `factorial`

.

```
def product(n, term):
"""Return the product of the first n terms in a sequence.
n -- a positive integer
term -- a function that takes one argument
>>> 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
"""
"*** YOUR CODE HERE ***"
def factorial(n):
"""Return n factorial for n >= 0 by calling product.
>>> factorial(4)
24
>>> factorial(6)
720
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'factorial', ['Recursion', 'For', 'While'])
True
"""
"*** YOUR CODE HERE ***"
return _______
```

Use OK to test your code:

```
python3 ok -q product
python3 ok -q factorial
```

### Question 2: Accumulate

Show that both `summation`

and `product`

are instances of a more
general function, called `accumulate`

, with the following signature:

```
from operator import add, mul
def accumulate(combiner, base, n, term):
"""Return the result of combining the first N terms in a sequence. The
terms to be combined are TERM(1), TERM(2), ..., TERM(N). COMBINER is a
two-argument function. Treating COMBINER as if it were a binary operator,
the return value is
BASE COMBINER TERM(1) COMBINER TERM(2) ... COMBINER TERM(N)
>>> 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
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
"""
"*** YOUR CODE HERE ***"
```

`accumulate(combiner, base, n, term)`

takes the following arguments:

`term`

and`n`

: the same arguments as in`summation`

and`product`

`combiner`

: a two-argument function that specifies how the current term combined with the previously accumulated terms.`base`

: value that specifies what value to use to start the accumulation.

For example, `accumulate(add, 11, 3, square)`

is

`11 + square(1) + square(2) + square(3)`

Implement `accumulate`

and show how `summation`

and `product`

can both be
defined as simple calls to `accumulate`

:

```
def summation_using_accumulate(n, term):
"""Returns the sum of TERM(1) + ... + TERM(N). The implementation
uses accumulate.
>>> summation_using_accumulate(5, square)
55
>>> summation_using_accumulate(5, triple)
45
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'summation_using_accumulate',
... ['Recursion', 'For', 'While'])
True
"""
"*** YOUR CODE HERE ***"
return _______
def product_using_accumulate(n, term):
"""An implementation of product using accumulate.
>>> product_using_accumulate(4, square)
576
>>> product_using_accumulate(6, triple)
524880
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'product_using_accumulate',
... ['Recursion', 'For', 'While'])
True
"""
"*** YOUR CODE HERE ***"
return _______
```

Use OK to test your code:

```
python3 ok -q accumulate
python3 ok -q summation_using_accumulate
python3 ok -q product_using_accumulate
```

### Question 3: Filtered Accumulate

Show to extend the `accumulate`

function to allow for *filtering* the results
produced by its `term`

argument. The function `filtered_accumulate`

has the
following signature:

```
def true(x):
return True
def false(x):
return False
def odd(x):
return x % 2 == 1
def filtered_accumulate(combiner, base, pred, n, term):
"""Return the result of combining the terms in a sequence of N terms
that satisfy the predicate PRED. COMBINER is a two-argument function.
If v1, v2, ..., vk are the values in TERM(1), TERM(2), ..., TERM(N)
that satisfy PRED, then the result is
BASE COMBINER v1 COMBINER v2 ... COMBINER vk
(treating COMBINER as if it were a binary operator, like +). The
implementation uses accumulate.
>>> filtered_accumulate(add, 0, true, 5, identity) # 0 + 1 + 2 + 3 + 4 + 5
15
>>> filtered_accumulate(add, 11, false, 5, identity) # 11
11
>>> filtered_accumulate(add, 0, odd, 5, identity) # 0 + 1 + 3 + 5
9
>>> filtered_accumulate(mul, 1, odd, 5, square) # 1 * 1 * 9 * 25
225
>>> # Do not use while/for loops or recursion
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'filtered_accumulate',
... ['While', 'For', 'Recursion', 'FunctionDef'])
True
"""
"*** YOUR CODE HERE ***"
return _______
```

`filtered_accumulate(combiner, base, pred, n, term)`

takes
the following arguments:

`combiner`

,`base`

,`term`

and`n`

: the same arguments as`accumulate`

.`pred`

: a one-argument predicate function applied to the values of`term`

. Only values for which`pred`

returns a true value are combined to form the result. If no values satisfy`pred`

, then`base`

is returned.

For example, `filtered_accumulate(add, 0, is_prime, 11, identity)`

would be

`0 + 2 + 3 + 5 + 7 + 11`

for a suitable definition of `is_prime`

.

Implement `filtered_accumulate`

with a single **return** statement containing
a call to `accumulate`

. Do not write any loops, **def** statements, or
recursive calls to `filtered_accumulate`

.

Hint: It may be useful to use one line if-else statements, otherwise known as ternary operators. The syntax is described in the Python documentation:The expression

`x if C else y`

first evaluates the condition,`C`

rather than`x`

. If`C`

is true,`x`

is evaluated and its value is returned; otherwise,`y`

is evaluated and its value is returned

Use OK to test your code:

`python3 ok -q filtered_accumulate`

### Question 4: Repeated

Implement `repeated(f, n)`

:

`f`

is a one-argument function that takes a number and returns another number.`n`

is a non-negative integer

`repeated`

returns another function that, when given an argument `x`

, will
compute `f(f(....(f(x))....))`

(apply `f`

a total `n`

times). For example,
`repeated(square, 3)(42)`

evaluates to `square(square(square(42)))`

.
Yes, it makes sense to apply the function zero times! See if you can
figure out a reasonable function to return for that case.

```
def repeated(f, n):
"""Return the function that computes the nth application of f.
>>> add_three = repeated(increment, 3)
>>> add_three(5)
8
>>> repeated(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1
243
>>> repeated(square, 2)(5) # square(square(5))
625
>>> repeated(square, 4)(5) # square(square(square(square(5))))
152587890625
>>> repeated(square, 0)(5)
5
"""
"*** YOUR CODE HERE ***"
```

*Hint*: You may find it convenient to use `compose1`

from the textbook:

```
def compose1(f, g):
"""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h
```

Use OK to test your code:

`python3 ok -q repeated`

### Question 5: G function

A mathematical function `G`

on positive integers is defined by two
cases:

```
G(n) = n, if n <= 3
G(n) = G(n - 1) + 2 * G(n - 2) + 3 * G(n - 3), if n > 3
```

Write a recursive function `g`

that computes `G(n)`

. Then, write an
iterative function `g_iter`

that also computes `G(n)`

:

```
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'g', ['While', 'For'])
True
"""
"*** YOUR CODE HERE ***"
def g_iter(n):
"""Return the value of G(n), computed iteratively.
>>> g_iter(1)
1
>>> g_iter(2)
2
>>> g_iter(3)
3
>>> g_iter(4)
10
>>> g_iter(5)
22
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion'])
True
"""
"*** YOUR CODE HERE ***"
```

Use OK to test your code:

```
python3 ok -q g
python3 ok -q g_iter
```

### Question 6: 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 7 or contains the digit 7. The first 30 elements of the ping-pong
sequence are listed below, with direction swaps marked using brackets at the
7th, 14th, 17th, 21st, 27th, and 28th elements:

`1 2 3 4 5 6 [7] 6 5 4 3 2 1 [0] 1 2 [3] 2 1 0 [-1] 0 1 2 3 4 [5] [4] 5 6`

Implement a function `pingpong`

that returns the nth element of the
ping-pong sequence. *Do not use any assignment statements; however, you
may use def statements*.

Hint: If you're stuck, try implementing`pingpong`

first using assignment and a`while`

statement. Any name that changes value will become an argument to a function in the recursive definition.

```
def pingpong(n):
"""Return the nth element of the ping-pong sequence.
>>> pingpong(7)
7
>>> pingpong(8)
6
>>> pingpong(15)
1
>>> pingpong(21)
-1
>>> pingpong(22)
0
>>> pingpong(30)
6
>>> pingpong(68)
2
>>> pingpong(69)
1
>>> pingpong(70)
0
>>> pingpong(71)
1
>>> pingpong(72)
0
>>> pingpong(100)
2
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'pingpong', ['Assign', 'AugAssign'])
True
"""
"*** YOUR CODE HERE ***"
```

Use OK to test your code:

`python3 ok -q pingpong`

You may use the function `has_seven`

, which returns True if a number `k`

contains the digit 7 at least once.

```
def has_seven(k):
"""Returns True if at least one of the digits of k is a 7, False otherwise.
>>> has_seven(3)
False
>>> has_seven(7)
True
>>> has_seven(2734)
True
>>> has_seven(2634)
False
>>> has_seven(734)
True
>>> has_seven(7777)
True
"""
if k % 10 == 7:
return True
elif k < 10:
return False
else:
return has_seven(k // 10)
```

### Question 7: Count change

Once the machines take over, the denomination of every coin will be a power of two: 1-cent, 2-cent, 4-cent, 8-cent, 16-cent, etc. There will be no limit to how much a coin can be worth.

A set of coins makes change for `n`

if the sum of the values of the
coins is `n`

. For example, the following sets make change for `7`

:

- 7 1-cent coins
- 5 1-cent, 1 2-cent coins
- 3 1-cent, 2 2-cent coins
- 3 1-cent, 1 4-cent coins
- 1 1-cent, 3 2-cent coins
- 1 1-cent, 1 2-cent, 1 4-cent coins

Thus, there are 6 ways to make change for `7`

. Write a function
`count_change`

that takes a positive integer `n`

and returns the number
of ways to make change for `n`

using these coins of the future:

```
def count_change(amount):
"""Return the number of ways to make change for amount.
>>> count_change(7)
6
>>> count_change(10)
14
>>> count_change(20)
60
>>> count_change(100)
9828
"""
"*** YOUR CODE HERE ***"
```

Use OK to test your code:

`python3 ok -q count_change`

### Question 8: Towers of Hanoi

A classic puzzle called the Towers of Hanoi is a game that consists of three
rods, and a number of disks of different sizes which can slide onto any rod.
The puzzle starts with `n`

disks in a neat stack in ascending order of size on
a `start`

rod, the smallest at the top, forming a conical shape.

The objective of the puzzle is to move the entire stack to an `end`

rod,
obeying the following rules:

- Only one disk may be moved at a time.
- Each move consists of taking the top (smallest) disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
- No disk may be placed on top of a smaller disk.

Complete the definition of `move_stack`

, which prints out the steps required to
move `n`

disks from the `start`

rod to the `end`

rod without violating the
rules.

```
def print_move(origin, destination):
"""Print instructions to move a disk."""
print("Move the top disk from rod", origin, "to rod", destination)
def move_stack(n, start, end):
"""Print the moves required to move n disks on the start pole to the end
pole without violating the rules of Towers of Hanoi.
n -- number of disks
start -- a pole position, either 1, 2, or 3
end -- a pole position, either 1, 2, or 3
There are exactly three poles, and start and end must be different. Assume
that the start pole has at least n disks of increasing size, and the end
pole is either empty or has a top disk larger than the top n start disks.
>>> move_stack(1, 1, 3)
Move the top disk from rod 1 to rod 3
>>> move_stack(2, 1, 3)
Move the top disk from rod 1 to rod 2
Move the top disk from rod 1 to rod 3
Move the top disk from rod 2 to rod 3
>>> move_stack(3, 1, 3)
Move the top disk from rod 1 to rod 3
Move the top disk from rod 1 to rod 2
Move the top disk from rod 3 to rod 2
Move the top disk from rod 1 to rod 3
Move the top disk from rod 2 to rod 1
Move the top disk from rod 2 to rod 3
Move the top disk from rod 1 to rod 3
"""
assert 1 <= start <= 3 and 1 <= end <= 3 and start != end, "Bad start/end"
"*** YOUR CODE HERE ***"
```

Use OK to test your code:

`python3 ok -q move_stack`

## Extra questions

Extra questions are not worth extra credit and are entirely optional. They are designed to challenge you to think creatively!

### Question 9: Y combinator

The recursive factorial function can be written as a single expression by using a conditional expression.

```
>>> fact = lambda n: 1 if n == 1 else mul(n, fact(sub(n, 1)))
>>> fact(5)
120
```

However, this implementation relies on the fact (no pun intended) that
`fact`

has a name, to which we refer in the body of `fact`

. To write a
recursive function, we have always given it a name using a `def`

or
assignment statement so that we can refer to the function within its
own body. In this question, your job is to define fact recursively
without giving it a name!

There's actually a general way to do this that uses a function `Y`

defined

```
def Y(f):
return f(lambda: Y(f))
```

Using this function, you can define `fact`

with an assignment statement
like this:

` fact = Y(?)`

where ? is an expression containing *only* lambda expressions,
conditional expressions, function calls, and the functions `mul`

and
`sub`

. That is, ? contains no statements (no assignments or **def**
statements in particular), and no mention of `fact`

or any other
identifier defined outside `?`

other than `mul`

or `sub`

from the `operator`

module. You are also allowed to use the equality (==)
operator. Find such an expression to use in place of `?`

.

```
from operator import sub, mul
def Y(f):
"""The Y ("paradoxical") combinator."""
return f(lambda: Y(f))
def Y_tester():
"""
>>> tmp = Y_tester()
>>> tmp(1)
1
>>> tmp(5)
120
>>> tmp(2)
2
"""
"*** YOUR CODE HERE ***"
return Y(________) # Replace
```

Use OK to test your code:

`python3 ok -q Y_tester`

### Question 10: Church numerals

The logician Alonzo Church invented a system of representing non-negative integers entirely using functions. The purpose was to show that functions are sufficient to describe all of number theory: if we have functions, we do not need to assume that numbers exist, but instead we can invent them.

Your goal in this problem is to rediscover this representation known as *Church
numerals*. Here are the definitions of `zero`

, as well as a function that
returns one more than its argument:

```
def zero(f):
return lambda x: x
def successor(n):
return lambda f: lambda x: f(n(f)(x))
```

First, define functions `one`

and `two`

such that they have the same behavior
as `successor(zero)`

and `successsor(successor(zero))`

respectively, but *do
not call successor in your implementation*.

Next, implement a function `church_to_int`

that converts a church numeral
argument to a regular Python integer.

Finally, implement functions `add_church`

, `mul_church`

, and `pow_church`

that
perform addition, multiplication, and exponentiation on church numerals.

```
def one(f):
"""Church numeral 1: same as successor(zero)"""
"*** YOUR CODE HERE ***"
def two(f):
"""Church numeral 2: same as successor(successor(zero))"""
"*** YOUR CODE HERE ***"
three = successor(two)
def church_to_int(n):
"""Convert the Church numeral n to a Python integer.
>>> church_to_int(zero)
0
>>> church_to_int(one)
1
>>> church_to_int(two)
2
>>> church_to_int(three)
3
"""
"*** YOUR CODE HERE ***"
def add_church(m, n):
"""Return the Church numeral for m + n, for Church numerals m and n.
>>> church_to_int(add_church(two, three))
5
"""
"*** YOUR CODE HERE ***"
def mul_church(m, n):
"""Return the Church numeral for m * n, for Church numerals m and n.
>>> four = successor(three)
>>> church_to_int(mul_church(two, three))
6
>>> church_to_int(mul_church(three, four))
12
"""
"*** YOUR CODE HERE ***"
def pow_church(m, n):
"""Return the Church numeral m ** n, for Church numerals m and n.
>>> church_to_int(pow_church(two, three))
8
>>> church_to_int(pow_church(three, two))
9
"""
"*** YOUR CODE HERE ***"
```

Use OK to test your code:

```
python3 ok -q church_to_int
python3 ok -q add_church
python3 ok -q mul_church
python3 ok -q pow_church
```