Python 如何最好地为我的树类编写一个_str_____)方法?
我有一个名为Python 如何最好地为我的树类编写一个_str_____)方法?,python,class,methods,tree,Python,Class,Methods,Tree,我有一个名为Tree的类: class Tree: def __init__(self, tag, children): self.tag = tag self.children = children def __str__(self): pass 这是我的类的一个示例对象: tree = Tree('A', [Tree('B', [Tree('C', [])]), Tree('D', [Tree('E', [])])]) 现在
Tree
的类:
class Tree:
def __init__(self, tag, children):
self.tag = tag
self.children = children
def __str__(self):
pass
这是我的类的一个示例对象:
tree = Tree('A', [Tree('B', [Tree('C', [])]), Tree('D', [Tree('E', [])])])
现在,我希望打印树时,它如下所示:
(A(B C)(D E))
我的想法是在嵌套的树中循环并检查,直到找到一个空列表,它告诉我这个空列表属于树的一片叶子。然后我从那里向上构建它,并在我的标记和子项周围添加括号。迭代方法可能会奏效,但我认为递归在这里更合适
class Tree:
def __init__(self, tag, children):
self.tag = tag
self.children = children
def __str__(self):
# Recursively build up the full string
if self.children:
return f'({self.tag} {" ".join(str(child) for child in self.children)})'
# Base case - no children; Just return the tag.
else:
return self.tag
这将生成所需的字符串:
>>> tree = Tree('A', [Tree('B', [Tree('C', [])]), Tree('D', [Tree('E', [])])])
>>> print(tree)
(A (B C) (D E))
在我看来,将子项分组在自己的括号中会更有意义,如下所示(为清晰起见,添加了额外的“F”节点): 可以通过将
else
返回括在括号中来实现:
class Tree:
...
def __str__(self):
...
else:
return f'({self.tag})'
但当然,这取决于您的使用是否正确:)这里没有问题。这里没有问题,除了:这需要实施,但仍然没有。您尝试过什么吗?您只需在uuu str_uuu()下发出
print()
命令,可能类似于print(“.join([self.tag]+self.children)),而不是return“。join([self.tag]+self.children)
class Tree:
...
def __str__(self):
...
else:
return f'({self.tag})'