使用给定的类Trees实现Generator函数

时间:2019-07-29 03:26:16

标签: python-3.7.4

类树:     “”“

  
    
      

t =树(3,[树(2,[树(5)]),树(4)])       标签           3       t.branches [0]。标签           2       t.branches [1] .is_leaf()           真正           “”           def init (自身,标签,分支= []):               对于分支中的b:                   断言isinstance(b,Tree)               self.label =标签               self.branches =列表(分支)

    
  
def is_leaf(self):
    return not self.branches

def map(self, fn):
    """
    Apply a function `fn` to each node in the tree and mutate the tree.

    >>> t1 = Tree(1)
    >>> t1.map(lambda x: x + 2)
    >>> t1.map(lambda x : x * 4)
    >>> t1.label
    12
    >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])
    >>> t2.map(lambda x: x * x)
    >>> t2
    Tree(9, [Tree(4, [Tree(25)]), Tree(16)])
    """
    self.label = fn(self.label)
    for b in self.branches:
        b.map(fn)

def __contains__(self, e):
    """
    Determine whether an element exists in the tree.

    >>> t1 = Tree(1)
    >>> 1 in t1
    True
    >>> 8 in t1
    False
    >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])
    >>> 6 in t2
    False
    >>> 5 in t2
    True
    """
    if self.label == e:
        return True
    for b in self.branches:
        if e in b:
            return True
    return False

def __repr__(self):
    if self.branches:
        branch_str = ', ' + repr(self.branches)
    else:
        branch_str = ''
    return 'Tree({0}{1})'.format(self.label, branch_str)

def __str__(self):
    def print_tree(t, indent=0):
        tree_str = '  ' * indent + str(t.label) + "\n"
        for b in t.branches:
            tree_str += print_tree(b, indent + 1)
        return tree_str
    return print_tree(self).rstrip()

def generate_paths(t,x):     “”“产生从t的根到带有标签x的节点的所有可能路径     作为列表。

>>> t1 = Tree(1, [Tree(2, [Tree(3), Tree(4, [Tree(6)]), Tree(5)]), Tree(5)])
>>> print(t1)
1
  2
    3
    4
      6
    5
  5
>>> next(generate_paths(t1, 6))
[1, 2, 4, 6]
>>> path_to_5 = generate_paths(t1, 5)
>>> sorted(list(path_to_5))
[[1, 2, 5], [1, 5]]

>>> t2 = Tree(0, [Tree(2, [t1])])
>>> print(t2)
0
  2
    1
      2
        3
        4
          6
        5
      5
>>> path_to_2 = generate_paths(t2, 2)
>>> sorted(list(path_to_2))
[[0, 2], [0, 2, 1, 2]]
"""

"*** YOUR CODE HERE ***"

for _______________ in _________________:
    for _______________ in _________________:

我需要基于给定的类来实现生成器功能

0 个答案:

没有答案