>> t = Tree(3, [Tree(2, [Tree(5)]), -6ren">
gpt4 book ai didi

python - 返回树中的值列表

转载 作者:行者123 更新时间:2023-12-01 07:04:02 24 4
gpt4 key购买 nike

我有这个树类,我正在创建一个函数,该函数将返回树中所有值的列表。

这是树类:

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:

您正在评估函数的真实性。该函数已定义,因此是 Truthy。

要实际测试函数调用的结果,请使用: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)]

关于python - 返回树中的值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58515034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com