python - 在树中实现 children.children

标签 python algorithm tree

我正在尝试实现在树结构中获取 child 的 child 的可能性。

这是我想要的例子。

enter image description here

到目前为止我做了什么。

class Children(list):

    def __init__(self, l):
        list.__init__(l)
        self.l = l

    @property
    def children(self):
        _children = []
        for child in self.l:
            _children.extend(child.children)
        return Children(_children)


class Person:

    def __init__(self):
        self._children = Children([])

    def add_child(self, child):
        self._children += [child]

    @property
    def children(self):
        return self._children


me = Person()
sister = Person()
brother = Person()
father = Person()
cousin = Person()
uncle = Person()
grandpa = Person()
ancient_grandpa = Person()

father.add_child(me)
father.add_child(sister)
father.add_child(brother)

uncle.add_child(cousin)

grandpa.add_child(father)
grandpa.add_child(uncle)

ancient_grandpa.add_child(grandpa)

print ancient_grandpa                             # ancient_grandpa
print ancient_grandpa.children                    # [grandpa]
print ancient_grandpa.children.children           # [father, uncle] but got []
print ancient_grandpa.children.children.children  # [me, sister, brother, cousin] but got []

请注意,这只是一个最小的工作示例。事实上,我的树比这更深。

最佳答案

在处理树时,最常见的方法是使用递归从树中提取数据和修改。

你也许可以这样做:

class Person(object):
    def __init__(self, name):
        self.name = name
        self.children = []

    def get_generation_n(self, n):
        if n <= 0:
            return []

        if n == 1:
            return self.children

        generation = []
        for child in self.children:
            generation += child.get_generation_n(n - 1)

        return generation

    def add_child(self, person):
        self.children.append(person)

    def __repr__(self):
        return self.name


grandpa = Person('Grand-Pa')
p1 = Person('p1')
p2 = Person('p2')
p3 = Person('p3')
p4 = Person('p4')
p5 = Person('p5')

p3.add_child(p5)
p3.add_child(p4)
p1.add_child(p2)
grandpa.add_child(p1)
grandpa.add_child(p3)

print(grandpa.get_generation_n(1)) # prints [p1, p3]
print(grandpa.get_generation_n(2)) # prints [p2, p4, p5]

事实上,你只需要一个类。对于 child 来说,只是另一个人。

关于python - 在树中实现 children.children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47574277/

相关文章:

java - 创建LinkedList的最小数和加法函数

mysql - 为 mysql/模糊搜索实现 Levenshtein 距离?

python - 在 pip.conf 中指定多个可信主机

python - 移位运算符和二进制按位运算符适用于 bool 参数

python - Scrapy:根据从自定义配置读取的值覆盖 DEPTH_LIMIT 变量

java - 预排序决策二叉树打印输出

c++ - 在 C++ 中反序列化树的最快方法是什么

python - 如何根据多索引 pandas 数据框中的行索引值创建列?

python - 递归找零算法

javascript - 在 AngularJS 中使用 ng-repeat 列出树结构时出错