python - 如何最好地为我的树类编写一个 __str__ 方法?
问题描述
我有一个名为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))
我的想法是遍历嵌套的 Trees 并检查直到找到一个空列表,它告诉我这个空列表属于我的树的一个叶子。然后我从那里向上构建它并在我的标签和孩子周围添加括号。
解决方案
迭代方法可能会起作用,但我认为递归在这里更合适。
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))
IMO,像这样将子子项分组在自己的括号中会更有意义(为清楚起见,添加了额外的“F”节点):
(A (B (C)) (D (E)) (F))
您可以通过将else
return 括在括号中来做到这一点:
class Tree:
...
def __str__(self):
...
else:
return f'({self.tag})'
但是,当然,这取决于您的用法是否正确:)
推荐阅读
- php - 2 个 Laravel 8 应用程序,具有自己的包、提供程序和缓存,但共享应用程序类
- python - 在 Python 3 中乘以大矩阵
- c++ - 为什么我会因此遇到分段错误?
- c++ - Why is this part repeated three times?
- c++ - looking for malloc in shared library
- javascript - Image not scaling to full width of div element
- python - How to associate class predictions with scores values of f1_score
- excel - 为什么我的用户定义函数不显示结果 VBA
- android - 如何去除线性布局的背景?
- excel - 有没有办法将在 Excel 中选择的范围导入我的 Web 应用程序?