这个python代码非常适合打印一棵树

2024-04-19 21:47:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白为什么会出现这种情况,我仍在努力学习python调试。你知道吗

class Node():
    def __init__(self, parent = None, children = [], data = None):
        self.parent = parent
        self.children = children
        self.data = data
        if parent == None:
            self.root = self
        else:
            self.root = self.parent.root

    def add_child(self, child):
        self.children.append(child)
        child.parent = self


    def is_root(self):
        return self.root == self

    def is_leaf(self):
        return self.children == []

    def is_empty(self):
        return self.data == None

    def pprint(self):
        def _pprint(ast, l):
            if not self.is_empty():
                print(l * " ", self.data)
            if not self.is_leaf():
                for child in self.children:
                    _pprint(child, l + 1)

        _pprint(self, 0)

我这样使用代码:

root = Node()
root.add_child(Node(data="a"))
root.pprint()

一段时间后,pprint方法会给出一个异常:

...
  File "ll.py", line 56, in _pprint
    _pprint(child, l + 1)
  File "ll.py", line 56, in _pprint
    _pprint(child, l + 1)
  File "ll.py", line 56, in _pprint
    _pprint(child, l + 1)
  File "ll.py", line 56, in _pprint
    _pprint(child, l + 1)
  File "ll.py", line 52, in _pprint
    if not self.is_empty():
  File "ll.py", line 48, in is_empty
    return self.data == None
RecursionError: maximum recursion depth exceeded in comparison

我认为“基本情况”应该是叶节点,没有子节点。我错过了什么?你知道吗


Tags: inpyselfnonechilddataisdef
1条回答
网友
1楼 · 发布于 2024-04-19 21:47:48
def __init__(self, parent = None, children = [], data = None):

所有节点都将使用相同的可变对象children。 这导致children像一个全局变量。你知道吗

阅读更多here。你知道吗

可能的解决方法:

def __init__(self, parent = None, children = None, data = None):
    if not children:
        self.children = []
    else:
        self.children = children

编辑:

当然,您还想在_pprint函数中写入ast,而不是self

def _pprint(ast, l):
    if not ast.is_empty():
        print(l * " ", ast.data)

    if not ast.is_leaf():
        for child in ast.children:
            _pprint(child, l + 1)

相关问题 更多 >