我有这个树类,并且正在创建一个函数,该函数将返回树中所有值的列表。
这是树类:
class Tree:
"""
>>> t = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])
>>> t.label
3
>>> t.branches[0].label
2
>>> t.branches[1].is_leaf()
True
"""
def __init__(self, label, branches=[]):
for b in branches:
assert isinstance(b, Tree)
self.label = label
self.branches = list(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 preorder(t):
"""Return a list of the entries in this tree in the order that they
would be visited by a preorder traversal (see problem description).
>>> numbers = Tree(1, [Tree(2), Tree(3, [Tree(4), Tree(5)]), Tree(6, [Tree(7)])])
>>> preorder(numbers)
[1, 2, 3, 4, 5, 6, 7]
>>> preorder(Tree(2, [Tree(4, [Tree(6)])]))
[2, 4, 6]
"""
result = []
result.append(t.label)
if t.is_leaf:
return result
else:
return result + [preorder(b) for b in t.branches]
但是,这不起作用。对于给出的示例,它仅返回[1]
。有人可以帮我理解为什么吗?
按照我的逻辑,我正在创建一个列表,并添加该功能所在的任何分支/树/叶子的标签。然后,我正在检查它是否是一片叶子。如果是一片叶子,我只返回列表,因为那意味着路径已经结束。否则,它将附加结果并继续沿树向下移动。
第一个问题是 if t.is_leaf:
您正在评估的真实性function
。该函数已定义,因此很真实。
要实际测试函数调用的结果,请使用: if t.is_leaf():
第二个问题是您正在创建列表列表:
使用return result + [preorder(b) for b in t.branches]
结果是[1, [2], [3, [4], [5]], [6, [7]]]
相反,您需要使用例如嵌套循环来解开那些子列表:
return result + [value for b in t.branches for value in preorder(b)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句