Homework 9
Due by 11:59pm on Monday, 8/7
Instructions
Download hw09.zip.
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.
Homework Questions
Iterators
Question 1: Link Iterable
To make theLink
class iterable, implement the LinkIterator
class.
class LinkIterator:
"""
>>> lnk = Link(1, Link(2, Link(3)))
>>> lnk_iter = LinkIterator(lnk)
>>> next(lnk_iter)
1
>>> next(lnk_iter)
2
"""
def __init__(self, link):
"*** YOUR CODE HERE ***"
def __iter__(self):
"*** YOUR CODE HERE ***"
def __next__(self):
"*** YOUR CODE HERE ***"
Use OK to test your code:
python3 ok -q LinkIterator
Generators
Question 2: In Order
Write a function that yields the entries of a valid binary search tree in sorted order.
def in_order(t):
"""
Yields the entries of a valid binary search tree in sorted order.
>>> b = BTree(5, BTree(3, BTree(2), BTree(4)), BTree(6))
>>> list(in_order(b))
[2, 3, 4, 5, 6]
>>> list(in_order(bst([1, 3, 5, 7, 9, 11, 13])))
[1, 3, 5, 7, 9, 11, 13]
>>> list(in_order(BTree(1)))
[1]
"""
"*** YOUR CODE HERE ***"
Hint: The
yield from
expression is helpful if you want to yield all the values from another sequence.
Use OK to test your code:
python3 ok -q in_order
Question 3: Generate Permutations
Given a list of unique elements, a permutation of the list is a
reordering of the elements. For example, [2, 1, 3]
, [1, 3, 2]
, and
[3, 2, 1]
are all permutations of the list [1, 2, 3]
.
Implement permutations
, a generator function that takes in a lst
and outputs
all permutations of lst
, each as a list (see doctest for an example).
def permutations(lst):
"""Generates all permutations of sequence LST. Each permutation is a
list of the elements in LST in a different order.
The order of the permutations does not matter.
>>> sorted(permutations([1, 2, 3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
>>> type(permutations([1, 2, 3]))
<class 'generator'>
>>> sorted(permutations((10, 20, 30)))
[[10, 20, 30], [10, 30, 20], [20, 10, 30], [20, 30, 10], [30, 10, 20], [30, 20, 10]]
>>> sorted(permutations("ab"))
[['a', 'b'], ['b', 'a']]
"""
if not lst:
yield []
return
"*** YOUR CODE HERE ***"
The order in which you generate permutations is irrelevant.
Hint: If you had the permutations of
lst
minus one element, how could you use that to generate the permutations of the fulllst
?
Use OK to test your code:
python3 ok -q permutations
Streams
Question 4: 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))
[]
"""
"*** YOUR CODE HERE ***"
Use OK to test your code:
python3 ok -q scale_stream
Question 5: 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 with1
.- The elements of
scale_stream(s, 2)
are also elements ofs
. - The same is true for
scale_stream(s, 3)
andscale_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
"*** YOUR CODE HERE ***"
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():
"*** YOUR CODE HERE ***"
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 6: 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.
>>> 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 CODE HERE ***"
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
Question 7: Stream of Streams
Write the functionmake_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_of_streams.rest
Stream(Stream(2, <...>), <...>)
>>> stream_of_streams.rest.rest
Stream(Stream(3, <...>), <...>)
>>> stream_of_streams
Stream(Stream(1, Stream(2, Stream(3, <...>))), Stream(Stream(2, Stream(3, <...>)), Stream(Stream(3, <...>), <...>)))
"""
"*** YOUR CODE HERE ***"
Use OK to test your code:
python3 ok -q make_stream_of_streams