2017-11-30 6 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] 

を、あなただけの1クラスが必要です。子供たちはちょうど別の人です。