# Lab 8: Midterm Review

*Due by 11:59pm on Tuesday, March 16.*

## Starter Files

Download lab08.zip. Inside the archive, you will find starter files for the questions in this lab, along with a copy of the Ok autograder.

## Submission

In order to facilitate midterm studying, solutions to this lab were released with the lab. We encourage you to try out the problems and struggle for a while before looking at the solutions!
**Note: You do not need to run** `python ok --submit`

**to receive credit for this assignment.**

# Required Questions

### Q1: All Questions Are Optional

The questions in this assignment are not graded, but they are highly recommended to help you prepare for the upcoming midterm. You will receive credit for this lab even if you do not complete these questions.

This question has no Ok tests.

# Suggested Questions

## Recursion and Tree Recursion

### Q2: Subsequences

A subsequence of a sequence `S`

is a subset of elements from `S`

, in the same
order they appear in `S`

. Consider the list `[1, 2, 3]`

. Here are a few of it's
subsequences `[]`

, `[1, 3]`

, `[2]`

, and `[1, 2, 3]`

.

Write a function that takes in a list and returns all possible subsequences of that list. The subsequences should be returned as a list of lists, where each nested list is a subsequence of the original input.

In order to accomplish this, you might first want to write a function `insert_into_all`

that takes an item and a list of lists, adds the item to the beginning of each nested list,
and returns the resulting list.

```
def insert_into_all(item, nested_list):
"""Return a new list consisting of all the lists in nested_list,
but with item added to the front of each. You can assuming that
nested_list is a list of lists.
>>> nl = [[], [1, 2], [3]]
>>> insert_into_all(0, nl)
[[0], [0, 1, 2], [0, 3]]
"""
"*** YOUR CODE HERE ***"
def subseqs(s):
"""Return a nested list (a list of lists) of all subsequences of S.
The subsequences can appear in any order. You can assume S is a list.
>>> seqs = subseqs([1, 2, 3])
>>> sorted(seqs)
[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
>>> subseqs([])
[[]]
"""
if ________________:
________________
else:
________________
________________
```

Use Ok to test your code:

`python3 ok -q subseqs`

### Q3: Non-Decreasing Subsequences

Just like the last question, we want to write a function that takes a list and returns a list of lists, where each individual list is a subsequence of the original input.

This time we have another condition: we only want the subsequences for which
consecutive elements are *nondecreasing*. For example, `[1, 3, 2]`

is a
subsequence of `[1, 3, 2, 4]`

, but since 2 < 3, this subsequence would *not*
be included in our result.

**Fill in the blanks** to complete the implementation of the `inc_subseqs`

function. You may assume that the input list contains no negative elements.

You may use the provided helper function `insert_into_all`

, which takes in an
`item`

and a list of lists and inserts the `item`

to the front of each list.

```
def non_decrease_subseqs(s):
"""Assuming that S is a list, return a nested list of all subsequences
of S (a list of lists) for which the elements of the subsequence
are strictly nondecreasing. The subsequences can appear in any order.
>>> seqs = non_decrease_subseqs([1, 3, 2])
>>> sorted(seqs)
[[], [1], [1, 2], [1, 3], [2], [3]]
>>> non_decrease_subseqs([])
[[]]
>>> seqs2 = non_decrease_subseqs([1, 1, 2])
>>> sorted(seqs2)
[[], [1], [1], [1, 1], [1, 1, 2], [1, 2], [1, 2], [2]]
"""
def subseq_helper(s, prev):
if not s:
return ____________________
elif s[0] < prev:
return ____________________
else:
a = ______________________
b = ______________________
return insert_into_all(________, ______________) + ________________
return subseq_helper(____, ____)
```

Use Ok to test your code:

`python3 ok -q non_decrease_subseqs`

### Q4: Number of Trees

A **full binary tree** is a tree where each node has either 2 branches or 0 branches, but never 1 branch.

Write a function which returns the number of unique full binary tree structures that have exactly n leaves.

For those interested in combinatorics, this problem does have a closed form solution):

```
def num_trees(n):
"""Returns the number of unique full binary trees with exactly n leaves. E.g.,
1 2 3 3 ...
* * * *
/ \ / \ / \
* * * * * *
/ \ / \
* * * *
>>> num_trees(1)
1
>>> num_trees(2)
1
>>> num_trees(3)
2
>>> num_trees(8)
429
"""
"*** YOUR CODE HERE ***"
```

Use Ok to test your code:

`python3 ok -q num_trees`

## Generators

### Q5: Merge

Implement `merge(incr_a, incr_b)`

, which takes two iterables `incr_a`

and `incr_b`

whose
elements are ordered. `merge`

yields elements from `incr_a`

and `incr_b`

in sorted
order, eliminating repetition. You may assume `incr_a`

and `incr_b`

themselves do not
contain repeats, and that none of the elements of either are `None`

.
You may **not** assume that the iterables are finite; either may produce an infinite
stream of results.

You will probably find it helpful to use the two-argument version of the built-in
`next`

function: `next(incr, v)`

is the same as `next(incr)`

, except that instead of
raising `StopIteration`

when `incr`

runs out of elements, it returns `v`

.

See the doctest for examples of behavior.

```
def merge(incr_a, incr_b):
"""Yield the elements of strictly increasing iterables incr_a and incr_b, removing
repeats. Assume that incr_a and incr_b have no repeats. incr_a or incr_b may or may not
be infinite sequences.
>>> m = merge([0, 2, 4, 6, 8, 10, 12, 14], [0, 3, 6, 9, 12, 15])
>>> type(m)
<class 'generator'>
>>> list(m)
[0, 2, 3, 4, 6, 8, 9, 10, 12, 14, 15]
>>> def big(n):
... k = 0
... while True: yield k; k += n
>>> m = merge(big(2), big(3))
>>> [next(m) for _ in range(11)]
[0, 2, 3, 4, 6, 8, 9, 10, 12, 14, 15]
"""
iter_a, iter_b = iter(incr_a), iter(incr_b)
next_a, next_b = next(iter_a, None), next(iter_b, None)
"*** YOUR CODE HERE ***"
```

Watch the hints video below for somewhere to start:

Use Ok to test your code:

`python3 ok -q merge`

## Objects

Minilecture Video: OOP

### Q6: Keyboard

We'd like to create a `Keyboard`

class that takes in an arbitrary
number of `Button`

s and stores these `Button`

s in a dictionary. The
keys in the dictionary will be ints that represent the postition on the
`Keyboard`

, and the values will be the respective `Button`

. Fill out
the methods in the `Keyboard`

class according to each description,
using the doctests as a reference for the behavior of a `Keyboard`

.

```
class Button:
"""
Represents a single button
"""
def __init__(self, pos, key):
"""
Creates a button
"""
self.pos = pos
self.key = key
self.times_pressed = 0
class Keyboard:
"""A Keyboard takes in an arbitrary amount of buttons, and has a
dictionary of positions as keys, and values as Buttons.
>>> b1 = Button(0, "H")
>>> b2 = Button(1, "I")
>>> k = Keyboard(b1, b2)
>>> k.buttons[0].key
'H'
>>> k.press(1)
'I'
>>> k.press(2) #No button at this position
''
>>> k.typing([0, 1])
'HI'
>>> k.typing([1, 0])
'IH'
>>> b1.times_pressed
2
>>> b2.times_pressed
3
"""
def __init__(self, *args):
________________
for _________ in ________________:
________________
def press(self, info):
"""Takes in a position of the button pressed, and
returns that button's output"""
if ____________________:
________________
________________
________________
________________
def typing(self, typing_input):
"""Takes in a list of positions of buttons pressed, and
returns the total output"""
________________
for ________ in ____________________:
________________
________________
```

Use Ok to test your code:

`python3 ok -q Keyboard`

### Q7: Bank Account

Implement the class `Account`

, which acts as a a Bank Account.
`Account`

should allow the account holder to deposit money into the account,
withdraw money from the account, and view their transaction history. The Bank Account
should also prevents a user from withdrawing more than the current balance.

Transaction history should be stored as a list of tuples, where each tuple contains the type of transaction and the transaction amount. For example a withdrawal of 500 should be stored as ('withdraw', 500)

Hint:You can call the`str`

function on an integer to get a string representation of the integer. You might find this function useful when implementing the`__repr__`

and`__str__`

methods.

Hint:You can alternatively use fstrings to implement the`__repr__`

and`__str__`

methods cleanly.

```
class Account:
"""A bank account that allows deposits and withdrawals.
It tracks the current account balance and a transaction
history of deposits and withdrawals.
>>> eric_account = Account('Eric')
>>> eric_account.deposit(1000000) # depositing paycheck for the week
1000000
>>> eric_account.transactions
[('deposit', 1000000)]
>>> eric_account.withdraw(100) # make a withdrawal to buy dinner
999900
>>> eric_account.transactions
[('deposit', 1000000), ('withdraw', 100)]
>>> print(eric_account) #call to __str__
Eric's Balance: $999900
>>> eric_account.deposit(10)
999910
>>> eric_account #call to __repr__
Accountholder: Eric, Deposits: 2, Withdraws: 1
"""
interest = 0.02
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
"*** YOUR CODE HERE ***"
def deposit(self, amount):
"""Increase the account balance by amount, add the deposit
to the transaction history, and return the new balance.
"""
"*** YOUR CODE HERE ***"
def withdraw(self, amount):
"""Decrease the account balance by amount, add the withdraw
to the transaction history, and return the new balance.
"""
"*** YOUR CODE HERE ***"
def __str__(self):
"*** YOUR CODE HERE ***"
def __repr__(self):
"*** YOUR CODE HERE ***"
```

Use Ok to test your code:

`python3 ok -q Account`

## Mutable Lists

### Q8: Trade

In the integer market, each participant has a list of positive integers to trade. When two participants meet, they trade the smallest non-empty prefix of their list of integers. A prefix is a slice that starts at index 0.

Write a function `trade`

that exchanges the first `m`

elements of list `first`

with the first `n`

elements of list `second`

, such that the sums of those
elements are equal, and the sum is as small as possible. If no such prefix
exists, return the string `'No deal!'`

and do not change either list. Otherwise
change both lists and return `'Deal!'`

. A partial implementation is provided.

Hint:You can mutate a slice of a list usingslice assignment. To do so, specify a slice of the list`[i:j]`

on the left-hand side of an assignment statement and another list on the right-hand side of the assignment statement. The operation will replace the entire given slice of the list from`i`

inclusive to`j`

exclusive with the elements from the given list. The slice and the given list need not be the same length.`>>> a = [1, 2, 3, 4, 5, 6] >>> b = a >>> a[2:5] = [10, 11, 12, 13] >>> a [1, 2, 10, 11, 12, 13, 6] >>> b [1, 2, 10, 11, 12, 13, 6]`

Additionally, recall that the starting and ending indices for a slice can be left out and Python will use a default value.

`lst[i:]`

is the same as`lst[i:len(lst)]`

, and`lst[:j]`

is the same as`lst[0:j]`

.

```
def trade(first, second):
"""Exchange the smallest prefixes of first and second that have equal sum.
>>> a = [1, 1, 3, 2, 1, 1, 4]
>>> b = [4, 3, 2, 7]
>>> trade(a, b) # Trades 1+1+3+2=7 for 4+3=7
'Deal!'
>>> a
[4, 3, 1, 1, 4]
>>> b
[1, 1, 3, 2, 2, 7]
>>> c = [3, 3, 2, 4, 1]
>>> trade(b, c)
'No deal!'
>>> b
[1, 1, 3, 2, 2, 7]
>>> c
[3, 3, 2, 4, 1]
>>> trade(a, c)
'Deal!'
>>> a
[3, 3, 2, 1, 4]
>>> b
[1, 1, 3, 2, 2, 7]
>>> c
[4, 3, 1, 4, 1]
"""
m, n = 1, 1
equal_prefix = lambda: ______________________
while _______________________________:
if __________________:
m += 1
else:
n += 1
if equal_prefix():
first[:m], second[:n] = second[:n], first[:m]
return 'Deal!'
else:
return 'No deal!'
```

Use Ok to test your code:

`python3 ok -q trade`

### Q9: Shuffle

Define a function `shuffle`

that takes a sequence with an even number of
elements (cards) and creates a new list that interleaves the elements
of the first half with the elements of the second half.

```
def card(n):
"""Return the playing card numeral as a string for a positive n <= 13."""
assert type(n) == int and n > 0 and n <= 13, "Bad card n"
specials = {1: 'A', 11: 'J', 12: 'Q', 13: 'K'}
return specials.get(n, str(n))
def shuffle(cards):
"""Return a shuffled list that interleaves the two halves of cards.
>>> shuffle(range(6))
[0, 3, 1, 4, 2, 5]
>>> suits = ['♡', '♢', '♤', '♧']
>>> cards = [card(n) + suit for n in range(1,14) for suit in suits]
>>> cards[:12]
['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧']
>>> cards[26:30]
['7♤', '7♧', '8♡', '8♢']
>>> shuffle(cards)[:12]
['A♡', '7♤', 'A♢', '7♧', 'A♤', '8♡', 'A♧', '8♢', '2♡', '8♤', '2♢', '8♧']
>>> shuffle(shuffle(cards))[:12]
['A♡', '4♢', '7♤', '10♧', 'A♢', '4♤', '7♧', 'J♡', 'A♤', '4♧', '8♡', 'J♢']
>>> cards[:12] # Should not be changed
['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧']
"""
assert len(cards) % 2 == 0, 'len(cards) must be even'
half = _______________
shuffled = []
for i in _____________:
_________________
_________________
return shuffled
```

Use Ok to test your code:

`python3 ok -q shuffle`

## Linked Lists

### Q10: Insert

Implement a function `insert`

that takes a `Link`

, a `value`

, and an
`index`

, and inserts the `value`

into the `Link`

at the given `index`

.
You can assume the linked list already has at least one element. Do not
return anything -- `insert`

should mutate the linked list.

Note: If the index is out of bounds, you should raise an`IndexError`

with:`raise IndexError('Out of bounds!')`

```
def insert(link, value, index):
"""Insert a value into a Link at the given index.
>>> link = Link(1, Link(2, Link(3)))
>>> print(link)
<1 2 3>
>>> other_link = link
>>> insert(link, 9001, 0)
>>> print(link)
<9001 1 2 3>
>>> link is other_link # Make sure you are using mutation! Don't create a new linked list.
True
>>> insert(link, 100, 2)
>>> print(link)
<9001 1 100 2 3>
>>> insert(link, 4, 5)
Traceback (most recent call last):
...
IndexError: Out of bounds!
"""
"*** YOUR CODE HERE ***"
```

Use Ok to test your code:

`python3 ok -q insert`

### Q11: Deep Linked List Length

A linked list that contains one or more linked lists as elements is called a
*deep* linked list. Write a function `deep_len`

that takes in a (possibly deep)
linked list and returns the *deep length* of that linked list. The deep length of
a linked list is the total number of non-link elements in the list, as well as the
total number of elements contained in all contained lists. See the function's doctests
for examples of the deep length of linked lists.

Hint:Use`isinstance`

to check if something is an instance of an object.

```
def deep_len(lnk):
""" Returns the deep length of a possibly deep linked list.
>>> deep_len(Link(1, Link(2, Link(3))))
3
>>> deep_len(Link(Link(1, Link(2)), Link(3, Link(4))))
4
>>> levels = Link(Link(Link(1, Link(2)), \
Link(3)), Link(Link(4), Link(5)))
>>> print(levels)
<<<1 2> 3> <4> 5>
>>> deep_len(levels)
5
"""
if ______________:
return 0
elif ______________:
return 1
else:
return _________________________
```

Use Ok to test your code:

`python3 ok -q deep_len`

### Q12: Linked Lists as Strings

Kevin and Jerry like different ways of displaying the linked list
structure in Python. While Kevin likes box and pointer diagrams,
Jerry prefers a more futuristic way. Write a function
`make_to_string`

that returns a function that converts the
linked list to a string in their preferred style.

*Hint*: You can convert numbers to strings using the `str`

function,
and you can combine strings together using `+`

.

```
>>> str(4)
'4'
>>> 'cs ' + str(61) + 'a'
'cs 61a'
```

```
def make_to_string(front, mid, back, empty_repr):
""" Returns a function that turns linked lists to strings.
>>> kevins_to_string = make_to_string("[", "|-]-->", "", "[]")
>>> jerrys_to_string = make_to_string("(", " . ", ")", "()")
>>> lst = Link(1, Link(2, Link(3, Link(4))))
>>> kevins_to_string(lst)
'[1|-]-->[2|-]-->[3|-]-->[4|-]-->[]'
>>> kevins_to_string(Link.empty)
'[]'
>>> jerrys_to_string(lst)
'(1 . (2 . (3 . (4 . ()))))'
>>> jerrys_to_string(Link.empty)
'()'
"""
def printer(lnk):
if ______________:
return _________________________
else:
return _________________________
return printer
```

Use Ok to test your code:

`python3 ok -q make_to_string`

## Trees

### Q13: Prune Small

Complete the function `prune_small`

that takes in a `Tree`

`t`

and a
number `n`

and prunes `t`

mutatively. If `t`

or any of its branches
has more than `n`

branches, the `n`

branches with the smallest labels
should be kept and any other branches should be *pruned*, or removed,
from the tree.

```
def prune_small(t, n):
"""Prune the tree mutatively, keeping only the n branches
of each node with the smallest label.
>>> t1 = Tree(6)
>>> prune_small(t1, 2)
>>> t1
Tree(6)
>>> t2 = Tree(6, [Tree(3), Tree(4)])
>>> prune_small(t2, 1)
>>> t2
Tree(6, [Tree(3)])
>>> t3 = Tree(6, [Tree(1), Tree(3, [Tree(1), Tree(2), Tree(3)]), Tree(5, [Tree(3), Tree(4)])])
>>> prune_small(t3, 2)
>>> t3
Tree(6, [Tree(1), Tree(3, [Tree(1), Tree(2)])])
"""
while ___________________________:
largest = max(_______________, key=____________________)
_________________________
for __ in _____________:
___________________
```

Use Ok to test your code:

`python3 ok -q prune_small`

### Q14: Long Paths

Implement `long_paths`

, which returns a list of all *paths* in a tree with
length at least `n`

. A path in a tree is a list of node labels that starts with
the root and ends at a leaf. Each subsequent element must be from a label of a
branch of the previous value's node. The *length* of a path is the number of
edges in the path (i.e. one less than the number of nodes in the path). Paths
are ordered in the output list from left to right in the tree. See the doctests
for some examples.

```
def long_paths(t, n):
"""Return a list of all paths in t with length at least n.
>>> long_paths(Tree(1), 0)
[[1]]
>>> long_paths(Tree(1), 1)
[]
>>> t = Tree(3, [Tree(4), Tree(4), Tree(5)])
>>> left = Tree(1, [Tree(2), t])
>>> mid = Tree(6, [Tree(7, [Tree(8)]), Tree(9)])
>>> right = Tree(11, [Tree(12, [Tree(13, [Tree(14)])])])
>>> whole = Tree(0, [left, Tree(13), mid, right])
>>> print(whole)
0
1
2
3
4
4
5
13
6
7
8
9
11
12
13
14
>>> for path in long_paths(whole, 2):
... print(path)
...
[0, 1, 2]
[0, 1, 3, 4]
[0, 1, 3, 4]
[0, 1, 3, 5]
[0, 6, 7, 8]
[0, 6, 9]
[0, 11, 12, 13, 14]
>>> for path in long_paths(whole, 3):
... print(path)
...
[0, 1, 3, 4]
[0, 1, 3, 4]
[0, 1, 3, 5]
[0, 6, 7, 8]
[0, 11, 12, 13, 14]
>>> long_paths(whole, 4)
[[0, 11, 12, 13, 14]]
"""
"*** YOUR CODE HERE ***"
```

Use Ok to test your code:

`python3 ok -q long_paths`

## Complexity

### Q15: Determining Complexity

Use Ok to test your knowledge with the following questions:

`python3 ok -q wwpd-complexity -u`

Be sure to ask a member of course staff if you don't understand the correct answer!

What is the order of growth of `is_prime`

in terms of `n`

?

```
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
```

*Explanation*: In the worst case, *n* is prime, and we have to execute the
loop *n* - 2 times. Each iteration takes constant time (one conditional check
and one return statement). Therefore, the total time is (*n* - 2) x constant,
or simply linear.

What is the order of growth of `bar`

in terms of `n`

?

```
def bar(n):
i, sum = 1, 0
while i <= n:
sum += biz(n)
i += 1
return sum
def biz(n):
i, sum = 1, 0
while i <= n:
sum += i**3
i += 1
return sum
```

*Explanation*: The body of the while loop in `bar`

is executed *n*
times. Each iteration, one call to `biz(n)`

is made. Note that *n* never
changes, so this call takes the same time to run each iteration. Taking a look at
`biz`

, we see that there is another while loop. Be careful to note that
although the term being added to `sum`

is cubed (`i**3`

), `i`

itself is only
incremented by 1 in each iteration. This tells us that this while loop also
executes *n* times, with each iteration taking constant time , so the total
time of `biz(n)`

is *n* x constant, or linear. Knowing the runtime of
linear, we can conclude that each iteration of the while loop in `bar`

is linear.
Therefore, the total runtime of `bar(n)`

is quadratic.