2017-06-11 2 views
0

私は、リストスタイル(例えば '[[p [q] [r]] [s]]')のツリーコードを持っています。 私のテキストブックでコードを使用して、葉を取得しようとしますが、コード(つまり、 'def print_tree_with_prefix')は再帰的ですので、メソッドを実行するたびに必要なデータが消去されます。誰もが何か考えを与えることができますか?ここ再帰のたびにデータを消去せずにself.astringをどのように保存できますか?

コードは次のとおり

class Tree: 

    def __init__(self, new_key): 
     self.key = new_key 
     # represent children of a node with a list 
     self.children = [] 
     # number of nodes in the subtree rooted at this node 
     self.num_of_descendants = 0  

    # prints the tree using the specified prefix for the current line 
    def print_tree_with_prefix(self, line_prefix, last_child): 
     self.astring = ''#it just erases the data as the method is recursive 
     count = 0 

     # generate the prefix for the next line 
     if len(self.children) > 0: 
      next_prefix = line_prefix 
      for child_index in range(len(self.children)-1): 
       self.children[child_index].print_tree_with_prefix(next_prefix, False) 
      self.children[-1].print_tree_with_prefix(next_prefix, True) 

     else: 
      self.newkey = self.key 
      self.astring = self.astring + self.key #add a new data in the string 
      print(self.astring) 

def load_tree(tree_str, pos = 0): 
    new_node = None 
    while pos < len(tree_str): 
     if tree_str[pos] == "[": 
      pos += 1 
      new_node = Tree(tree_str[pos]) 
      while pos < len(tree_str) and tree_str[pos + 1] != "]": 
       pos += 1 
       child_tree, pos = load_tree(tree_str, pos) 
       if child_tree: 
        new_node.children.append(child_tree) 
        new_node.num_of_descendants += \ 
         1 + child_tree.num_of_descendants 
      return new_node, pos + 1 
     else: 
      pos += 1 
    return new_node, pos 

def main(): 
    tree, processed_chars = load_tree('[o[p[q][r]][s]]') #the sample tree 
    tree.print_tree_with_prefix("", True) 

main() 

出力は、(個別の行で) Q R S

期待出力: QRS (全体CONCATENATE列)

'def print_tree_with_prefix'の 'else'部分がうまくいきません...誰かが助けてくれますか? :(

答えて

0

それはあなたがそれはあなたが、行くように、プリントアウトしたのではなく、出力を連結して単一の文字列を返すようにしようとしているように聞こえる?

ので、その後、それは簡単です行うには、あなたのアルゴリズムを変更した場合しかし、これはコードのはるかに簡単ピースに煮詰めすることができます(いくつかの未使用の変数を除去):

def print_tree_with_prefix(self): 
    if not self.children: 
     return self.key 
    return ''.join([child.print_tree_with_prefix() for child in self.children]) 

をして、それを起動します。

def main(): 
    tree, processed_chars = load_tree('[o[p[q][r]][s]]') 
    print tree.print_tree_with_prefix() 

が生成します:

qrs 

おそらく、ごくわずかな変更で元のアルゴリズムを修正する方法を検討する価値があります。

あなたが作っている重要な間違いは、それぞれの再帰呼び出しによって付加される変数astringが1つあると考えていると思います。

実際、Treeインスタンスごとに別の 'astring'変数があり、 `print_tree_with_prefix 'は値を返しません。

# prints the tree using the specified prefix for the current line 
def print_tree_with_prefix(self, line_prefix, last_child): 
    astring = ''#it just erases the data as the method is recursive 
    count = 0 

    # generate the prefix for the next line 
    if len(self.children) > 0: 
     next_prefix = line_prefix 
     for child_index in range(len(self.children)-1): 
      astring += self.children[child_index].print_tree_with_prefix(next_prefix, False) 
     astring += self.children[-1].print_tree_with_prefix(next_prefix, True) 
     return astring 
    else: 
     self.newkey = self.key 
     astring = astring + self.key #add a new data in the string 
     return astring 

をそして最後にそれを印刷:この問題を解決するために、我々は、単に親の呼び出しにデータを返すために、コードを変更することは、コードを簡略化するだけの場合であるとした後

def main(): 
    tree, processed_chars = load_tree('[o[p[q][r]][s]]') #the sample tree 
    print tree.print_tree_with_prefix("", True) 

をし、使用された変数を削除します。

+0

ありがとうございました!それは非常にうまく動作します! :) – hhh

+0

お寄せいただきありがとうございます、これを受け入れられる回答として設定してください。 – FujiApple

関連する問題