2017-11-30 1 views
0

트리 구조로 하위의 자식을 가져올 수있는 가능성을 구현하려고합니다.트리에서 children.children을 구현하십시오.

다음은 내가 원하는 것을 보여줍니다.

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 [] 

이것은 단지 최소한의 작동 예제입니다. 사실, 제 나무는 이것보다 더 깊습니다.

답변

3

트리를 사용하여 작업 할 때 재귀를 사용하여 데이터를 추출하고 트리에서 수정하는 것이 가장 일반적입니다.

당신은 아마 같은 것을 할 수있는 : 사실

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] 

을, 당신은 단지 하나 개의 클래스가 필요합니다. 아이들은 단지 다른 사람입니다.

관련 문제