2016-05-16 8 views
0

私はファミリーツリーを設計してリストを作ることを学んでいます。以下は私が思いついたのですが、結果を印刷するのに問題があります。う、私はリストのリストを印刷する

Aは2人の子供、B & C ... を持っている場合、Cは一人っ子でありながらBが ... 2人の子供、D & Eを持ち、F ...

例えば:

私のコードの改善、上記のような結果の印刷方法に関するアドバイス、またはそれをグラフィック形式で印刷します。

class FamilyTree: 
    def __init__(self, root): 
     self.name = root 
     self.children = [] 
     nmbr = int(input("How many children does " + root + " have? ")) 
     if nmbr is not 0: 
      for i, child in enumerate(range(nmbr)): 
       name = input("What is one of " + root + "'s child's name? ") 
       self.children.append(FamilyTree(name)) 
    def __str__(self): 
     return '[' + self.name + ''.join(', ' + str(c) for c in self.children) + ']' 
r = print(FamilyTree('A')) 
+0

あなたが構築している間、あなたは木を印刷することはできませんそれは...(それを順序通りに構築しない限り)。 – alfasin

+0

関連:[Pythonでのツリーデータ構造の印刷](http://stackoverflow.com/questions/20242479/printing-a-tree-data-structure-in-python) – DaoWen

答えて

0

あなたはprint()関数によって呼び出された__str__メソッドを使用することができます。また、setattrを使用すると、出力を書き込むのが難しくなります。ここで

あなたはFamilyTreeまたはユーザからの入力を読まずに作成することができるソリューションです。

class FamilyTree: 
    def __init__(self, root, childs = []): 
     self.name = root 
     self.childs = childs 

    def read(self): 
     nmbr = int(input("How many children does " + self.name + " have? ")) 
     if nmbr is not 0: 
      for _ in range(nmbr): 
       name = input("What is one of " + self.name + "'s child's name? ") 
       child = FamilyTree(name) 
       child.read() 
       self.childs.append(child) 

    def __repr__(self): 
     if len(self.childs) == 0: 
      return str("{}".format(self.name)) 
     else: 
      return str("{}, {}".format(self.name, self.childs)) 

# creates a FamilyTree directly so we can test the output 
r = FamilyTree(
     'A', 
     [ 
      FamilyTree(
       'B', 
       [FamilyTree('C'), FamilyTree('C')] 
      ), 
      FamilyTree(
       'C', 
       [FamilyTree('F')] 
      ) 
     ] 
    ) 

# or read input from the user 
# r = FamilyTree('A') 
# r.read() 

print(r) 

出力

A, [B, [C, C], C, [F]] 
0

これは、入力と出力からのオブジェクトの作成を分割することをお勧めします:

class FamilyTree: 
    def __init__(self, root): 
     self.name = [root] 
     nmbr = int(input("How many children does " + root + " have?")) 
     if nmbr is not 0: 
      for i, child in enumerate(range(nmbr)): 
       name = input("What is one of " + root + "'s child's name?") 
       setattr(self, "child{0}".format(i), FamilyTree(name)) 
r = print(FamilyTree('A')) 
関連する問題