Lab 7 - Midterm review

HOF, Recursion, Trees, Sequences & Mutability

Q1, Q2 & Q6 are non-coding (ENV Diagrams/What Would Python Do?)

I remember spending a long time, banging my head against the wall on Q4. 😇

Instructions: https://inst.eecs.berkeley.edu/~cs61a/su19/lab/lab07/arrow-up-right

Solution: https://github.com/tomthestrom/cs61a/blob/master/lab/lab07/lab07.pyarrow-up-right

Q3: Insect Combinatorics

Consider an insect in an M by N grid. The insect starts at the bottom left corner, (0, 0), and wants to end up at the top right corner, (M-1, N-1). The insect is only capable of moving right or up. Write a function paths that takes a grid length and width and returns the number of different paths the insect can take from the start to the goal. (There is a closed-form solution to this problem, but try to answer it procedurally using recursion.)

def paths(m, n):
    """Return the number of paths from one corner of an
    M by N grid to the opposite corner.

    >>> paths(2, 2)
    2
    >>> paths(5, 7)
    210
    >>> paths(117, 1)
    1
    >>> paths(1, 157)
    1
    """
    "*** YOUR CODE HERE ***"

Q3: Solution

Q4: Number of Trees

How many different possible full binary tree (each node has two branches or 0, but never 1) structures exist that have exactly n leaves?

For those interested in combinatorics, this problem does have a closed form solutionarrow-up-right):

Q4: Solution

Q5: Pruning Leaves

Define a function prune_leaves that given a tree t and a tuple of values vals, produces a version of t with all its leaves that are in vals removed. Do not attempt to try to remove non-leaf nodes and do not remove leaves that do not match any of the items in vals. Return None if pruning the tree results in there being no nodes left in the tree.

Q5: Solution

Last updated