Problem 3.3: Iterator Tree Link Tree Iterator (100 pts)
Implement the function funcs
, which is a generator that takes in a linked list link
and yields functions.
The linked list link
defines a path from the root of the tree to one of its nodes, with each element of link specifying which branch to take by index. Applying all functions sequentially to a Tree instance will evaluate to the label of the node at the end of the specified path.
For example, using the Tree t
defined in the code, funcs(Link(2))
yields 2 functions. The first gets the third branch from t -- the branch at index 2 -- and the second function gets the label of this branch.
>>> func_generator = funcs(Link(2)) # get label of third branch
>>> f1 = next(func_generator)
>>> f2 = next(func_generator)
>>> f2(f1(t))
4
def funcs(link):
"""
>>> t = Tree(1, [Tree(2,
... [Tree(5),
... Tree(6, [Tree(8)])]),
... Tree(3),
... Tree(4, [Tree(7)])])
>>> print(t)
1
2
5
6
8
3
4
7
>>> func_generator = funcs(Link.empty) # get root label
>>> f1 = next(func_generator)
>>> f1(t)
1
>>> func_generator = funcs(Link(2)) # get label of third branch
>>> f1 = next(func_generator)
>>> f2 = next(func_generator)
>>> f2(f1(t))
4
>>> # This just puts the 4 values from the iterable into f1, f2, f3, f4
>>> f1, f2, f3, f4 = funcs(Link(0, Link(1, Link(0))))
>>> f4(f3(f2(f1(t))))
8
>>> f4(f2(f1(t)))
6
"""
"*** YOUR CODE HERE ***"