Due by 11:59pm on Tuesday, 4/18

## Instructions

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. Check that you have successfully submitted your code on okpy.org. See Lab 0 for more 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:

# Homework Questions

## Some Review: Sets

One really convenient thing about Python sets is that many operations on sets (adding elements, removing elements, checking membership) run in θ(1) (constant) time (usually).

Some of the problems use a utility method called `timeit`, which takes a parameterless function as argument, executes it, and returns the time required to do so. It's a variation on the function `timeit.timeit` function in the Python3 library.

### Question 1: Missing Value

Write the following function so it (usually) runs in θ(n) time, where n is the length of `lst0`.

``````def missing_val(lst0, lst1):
"""Assuming that lst0 contains all the values in lst1, but lst1 is missing
one value in lst0, return the missing value.  The values need not be
numbers.

>>> from random import shuffle
>>> missing_val(range(10), [1, 0, 4, 5, 7, 9, 2, 6, 3])
8
>>> big0 = [str(k) for k in range(15000)]
>>> big1 = [str(k) for k in range(15000) if k != 293 ]
>>> shuffle(big0)
>>> shuffle(big1)
>>> missing_val(big0, big1)
'293'
>>> timeit(lambda: missing_val(big0, big1)) < 1.0
True
"""
``````

Use OK to test your code:

``python3 ok -q missing_val``

### Question 2: Find duplicates k

Write the following function so it runs in O(n) time.

Hint: Sets have an `add` and a `remove` method.

``````def find_duplicates_k(k, lst):
"""Returns True if there are any duplicates in lst that are within k
indices apart.

>>> find_duplicates_k(3, [1, 2, 3, 4, 1])
False
>>> find_duplicates_k(4, [1, 2, 3, 4, 1])
True
>>> find_duplicates_k(4, [1, 1, 2, 3, 3])
True
"""
``````

Use OK to test your code:

``python3 ok -q find_duplicates_k``

## More Review: Scheme

Note: Q3 and Q4 (Substitute, Sub All) were extra lab questions from Lab 9. You may check the solutions if you are stuck, but we highly recommend you work through the problem on your own for practice.

### Question 3: Substitute

Write a procedure `substitute` that takes three arguments: a list `s`, an `old` word, and a `new` word. It returns a list with the elements of `s`, but with every occurrence of `old` replaced by `new`, even within sub-lists.

Hint: The built-in `pair?` predicate returns True if its argument is a `cons` pair.

``````(define (substitute s old new)
'YOUR-CODE-HERE
)``````

Use OK to test your code:

``python3 ok -q substitute``

### Question 4: Sub All

Write `sub-all`, which takes a list `s`, a list of `old` words, and a list of `new` words; the last two lists must be the same length. It returns a list with the elements of `s`, but with each word that occurs in the second argument replaced by the corresponding word of the third argument.

``````(define (sub-all s olds news)
'YOUR-CODE-HERE
)``````

Use OK to test your code:

``python3 ok -q sub-all``

## Streams

### Question 5: Scale Stream

Implement the function `scale_stream`, which returns a stream over each element of an input stream, scaled by `k`:

``````def scale_stream(s, k):
"""Return a stream of the elements of S scaled by a number K.

>>> ints = make_integer_stream(1)
>>> s = scale_stream(ints, 5)
>>> stream_to_list(s, 5)
[5, 10, 15, 20, 25]
>>> s = scale_stream(Stream("x", lambda: Stream("y")), 3)
>>> stream_to_list(s)
['xxx', 'yyy']
>>> stream_to_list(scale_stream(Stream.empty, 10))
[]
"""
``````

Use OK to test your code:

``python3 ok -q scale_stream``

### Question 6: Regular Numbers

Acknowledgements. This exercise is taken from Structure and Interpretation of Computer Programs, Section 3.5.2.

A famous problem, first raised by Richard Hamming, is to enumerate, in ascending order with no repetitions, all positive integers with no prime factors other than 2, 3, or 5. These are called regular numbers. One obvious way to do this is to simply test each integer in turn to see whether it has any factors other than 2, 3, and 5. But this is very inefficient, since, as the integers get larger, fewer and fewer of them fit the requirement. As an alternative, we can build a stream of such numbers. Let us call the required stream of numbers `s` and notice the following facts about it.

• `s` begins with `1` .
• The elements of `scale_stream(s, 2)` are also elements of `s`.
• The same is true for `scale_stream(s, 3)` and `scale_stream(s, 5)`.
• These are all of the elements of `s`.

Now all we have to do is combine elements from these sources. For this we define a `merge` function that combines two ordered streams into one ordered result stream, eliminating repetitions.

Fill in the definition of `merge`, then fill in the definition of `make_s` below:

``````def merge(s0, s1):
"""Return a stream over the elements of strictly increasing s0 and s1,
removing repeats. Assume that s0 and s1 have no repeats.

>>> ints = make_integer_stream(1)
>>> twos = scale_stream(ints, 2)
>>> threes = scale_stream(ints, 3)
>>> m = merge(twos, threes)
>>> stream_to_list(m, 10)
[2, 3, 4, 6, 8, 9, 10, 12, 14, 15]
"""
if s0 is Stream.empty:
return s1
elif s1 is Stream.empty:
return s0

e0, e1 = s0.first, s1.first

def make_s():
"""Return a stream over all positive integers with only factors 2, 3, & 5.

>>> s = make_s()
>>> stream_to_list(s, 20)
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36]
"""
def rest():
s = Stream(1, rest)
return s``````

Use OK to test your code:

``python3 ok -q merge``

Use OK to test your code:

``python3 ok -q make_s``

### Question 7: Linear Congruential Generator

A common method of producing pseudo-random numbers is by means of the following recurrence relation:

• R0 = seed value
• Ri+1 = (a*Ri + c) % n where Ri denotes the ith pseudo-random number in the stream; a, c, and n are constant integers, and seed value is some initial value provided by the user or chosen automatically by the system.

Define a function that returns a stream of random numbers that uses this linear-congruential formula.

``````from operator import add, mul, mod

def make_random_stream(seed, a, c, n):
"""The infinite stream of pseudo-random numbers generated by the
recurrence r[0] = SEED, r[i+1] = (r[i] * A + C) % N.  Your solution
must not use any lambdas or def's that we have not supplied in the
skeleton.
>>> s = make_random_stream(25, 29, 5, 32)
>>> stream_to_list(s, 10)
[25, 26, 23, 0, 5, 22, 3, 28, 17, 18]
>>> s = make_random_stream(17, 299317, 13, 2**20)
>>> stream_to_list(s, 10)
[17, 894098, 115783, 383424, 775373, 994174, 941859, 558412, 238793, 718506]
"""

``````

Your solution must use only the functions defined in the skeleton, without defining any additional ones. Likewise, any lambda expressions should contain only calls to these functions.

Use OK to test your code:

``python3 ok -q make_random_stream``

## Extra questions

Extra questions are not worth extra credit and are entirely optional.

### Question 8: Stream of Streams

Write the function `make_stream_of_streams`, which returns an infinite stream, where the element at position `i`, counting from 1, is an infinite stream of integers that start from `i`. Your solution should have the form
``````result = Stream(..., lambda: ...)
return result``````

and should not require any additional helper functions (i.e., just use recursively defined streams, and any additional functions supplied in your starter file). You may find the `map_stream` function useful.

``````def make_stream_of_streams():
"""
>>> stream_of_streams = make_stream_of_streams()
>>> stream_of_streams
Stream(Stream(1, <...>), <...>)
>>> stream_to_list(stream_of_streams, 3)
[Stream(1, <...>), Stream(2, <...>), Stream(3, <...>)]
>>> stream_to_list(stream_of_streams, 4)
[Stream(1, <...>), Stream(2, <...>), Stream(3, <...>), Stream(4, <...>)]
"""
``````

Use OK to test your code:

``python3 ok -q make_stream_of_streams``

### Differentiation

The following problems develop a system for symbolic differentiation of algebraic expressions. The `derive` Scheme procedure takes an algebraic expression and a variable and returns the derivative of the expression with respect to the variable. Symbolic differentiation is of special historical significance in Lisp. It was one of the motivating examples behind the development of the language. Differentiating is a recursive process that applies different rules to different kinds of expressions:

``````; derive returns the derivative of EXPR with respect to VAR
(define (derive expr var)
(cond ((number? expr) 0)
((variable? expr) (if (same-variable? expr var) 1 0))
((sum? expr) (derive-sum expr var))
((product? expr) (derive-product expr var))
((exp? expr) (derive-exp expr var))
(else 'Error)))``````

To implement the system, we will use the following data abstraction. Sums and products are lists, and they are simplified on construction:

``````; Variables are represented as symbols
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))

; Numbers are compared with =
(define (=number? expr num)
(and (number? expr) (= expr num)))

(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list '+ a1 a2))))
(define (sum? x)
(and (list? x) (eq? (car x) '+)))

(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
(define (product? x)
(and (list? x) (eq? (car x) '*)))

### Question 9: Derive Sum

Implement `derive-sum`, a procedure that differentiates a sum by summing the derivatives of the `addend` and `augend`. Use data abstraction for a sum:

``````(define (derive-sum expr var)
'YOUR-CODE-HERE
)
``````

Use OK to test your code:

``python3 ok -q derive-sum``

### Question 10: Derive Product

Implement `derive-product`, which applies the product rule to differentiate products:

``````(define (derive-product expr var)
'YOUR-CODE-HERE
)
``````

Use OK to test your code:

``python3 ok -q derive-product``

### Question 11: Make Exp

Implement a data abstraction for exponentiation: a `base` raised to the power of an `exponent`. The `base` can be any expression, but assume that the `exponent` is a non-negative integer. You can simplify the cases when `exponent` is `0` or `1`, or when `base` is a number, by returning numbers from the constructor `make-exp`. In other cases, you can represent the exp as a triple `(^ base exponent)`.

Hint: The built-in procedure `expt` takes two number arguments and raises the first to the power of the second.

``````; Exponentiations are represented as lists that start with ^.
(define (make-exp base exponent)
'YOUR-CODE-HERE
)

(define (base exp)
'YOUR-CODE-HERE
)

(define (exponent exp)
'YOUR-CODE-HERE
)

(define (exp? exp)
'YOUR-CODE-HERE
)

(define x^2 (make-exp 'x 2))
(define x^3 (make-exp 'x 3))``````

Use OK to test your code:

``python3 ok -q make-exp``

### Question 12: Derive Exp

Implement `derive-exp`, which uses the power rule to derive exps:

``````(define (derive-exp exp var)
'YOUR-CODE-HERE
)
``````

Use OK to test your code:

``python3 ok -q derive-exp``