## Problem 4: Trictionary or Treat ![k_and_v](pic/k_and_v.png) A trictionary is a pair of tree `k` and `v`. They have identical structure: each node in `k` has a corresponding node in `v`. The labels in `k` are called keys. Each key may be the label for multiple nodes in `k`, and the values for that key are the labels of all the corresponding nodes in `v`. A lookup function returns one of the values for a key. Specifically, a lookup function for a node in `k` is a function that takes `v` as an argument and returns the label for the corresponding node in `v`. Implement the generator function `lookups`, which takes as input a tree `k` and a key. It yields all lookup functions for nodes in `k` that have key as their label, the functions could be yielded in any order. ```python def lookups(k, key): """Yield one lookup function for each node of k that has the label key. >>> k = tree(5, [tree(7, [tree(2)]), tree(8, [tree(3), tree(4)]), tree(5, [tree(4), tree(2)])]) >>> v = tree('Go', [tree('C', [tree('C')]), tree('A', [tree('S'), tree(6)]), tree('L', [tree(1), tree('A')])]) >>> type(lookups(k, 4)) <class 'generator'> >>> sorted([f(v) for f in lookups(k, 2)]) ['A', 'C'] >>> sorted([f(v) for f in lookups(k, 3)]) ['S'] >>> [f(v) for f in lookups(k, 6)] [] """ "*** YOUR CODE HERE ***" ```
时间: 2023-12-28 07:04:36 浏览: 18
这个问题是关于Python的树的数据结构的实现,需要实现一个生成器函数 `lookups`。这个函数的输入是一棵树 `k` 和一个键 `key`,它会返回与该键匹配的所有节点的查找函数。每个查找函数都是一个函数,它将 `v` 作为参数,并返回 `v` 中相应节点的标签。
下面是一个实现示例:
```python
def lookups(k, key):
"""
Yield one lookup function for each node of k that has the label key.
"""
if label(k) == key:
yield lambda v: label(v)
for b in branches(k):
yield from lookups(b, key)
```
这个函数首先检查 `k` 的根节点是否与给定的键 `key` 匹配。如果匹配,则生成一个匿名函数,该函数返回 `v` 的根节点标签。然后,它遍历 `k` 的所有子树,递归地调用 `lookups` 函数,并将结果与 `yield from` 一起返回。在这个过程中,如果子树的根节点的标签与 `key` 匹配,则生成一个查找函数。
下面是一个使用示例:
```python
k = tree(5, [tree(7, [tree(2)]), tree(8, [tree(3), tree(4)]), tree(5, [tree(4), tree(2)])])
v = tree('Go', [tree('C', [tree('C')]), tree('A', [tree('S'), tree(6)]), tree('L', [tree(1), tree('A')])])
print(type(lookups(k, 4))) # <class 'generator'>
print(sorted([f(v) for f in lookups(k, 2)])) # ['A', 'C']
print(sorted([f(v) for f in lookups(k, 3)])) # ['S']
print([f(v) for f in lookups(k, 6)]) # []
```