【问题标题】:adding childern to tree stucture and print将孩子添加到树结构并打印
【发布时间】:2022-01-27 04:20:57
【问题描述】:

我正在尝试根据这篇文章实现一个 n-arry 树: [这里][1] 并且在尝试定义添加子项的函数时出现错误:

    class node(object):
    def __init__(self, value, children = []):
        self.value = value
        self.children = children

    def __str__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__str__(level+1)
        return ret
    
    # trying to implement this method si that I can get rid of
    # calling root.children[0].children
    def add_child(self, obj):
        self.children.append(obj)
        
    def __repr__(self):
        return '<tree node representation>'

root = node('grandmother')
root.children = [node('daughter'), node('son')]
root.children[0].children = [node('granddaughter'), node('grandson')]
root.children[1].children = [node('granddaughter'), node('grandson')]
root.add_child([node((1)), node(2)]) # error 

print (root)

我希望能够创建一棵树并打印它。 [1]:Printing a Tree data structure in Python

【问题讨论】:

  • 不过,这个错误实际上说明了什么?
  • 您正在尝试将节点的 列表 添加为单个子节点。您要么需要一个 add_children 方法,该方法使用 self.children.extend 一次添加多个孩子,要么多次调用 add_child,每个孩子添加一个。

标签: python tree


【解决方案1】:

如果你命名一个方法add_child,它应该添加一个孩子,而不是孩子。如果您添加子项,您应该 extend 列表,而不仅仅是在其末尾附加给定列表。

工作示例:

class Node(object):
    def __init__(self, value, children=None):
        if children is None:
            children = []
        self.value = value
        self.children = children


    def __str__(self, level=0):
        ret = "\t" * level + repr(self.value) + "\n"
        for child in self.children:
            ret += child.__str__(level + 1)
        return ret

    def add_children(self, obj):
        self.children.extend(obj)


root = Node('grandmother')
root.children = [Node('daughter'), Node('son')]
root.children[0].children = [Node('granddaughter'), Node('grandson')]
root.children[1].children = [Node('granddaughter'), Node('grandson')]
root.add_children([Node(1), Node(2)])

print(root)

输出:

'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'
    1
    2

【讨论】:

    【解决方案2】:

    您使用整个列表对象调用add_child。在add_child 中,您使用list.append 方法将整个列表对象添加到列表本身。

    方案一:直接指定节点调用add_child

    root.add_child(node((1))
    root.add_child(node((2))
    

    解决方案 2:更改 add_child 的实现,使用 list.extend 而不是 list.append。前者将提供的参数中的每个元素添加到列表中,而后者将整个参数添加到列表中。

    def add_child(self, obj):
        self.children.extend(obj)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2011-05-09
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多