2017-03-04 2 views
1

と木の子としてリストを追加します。私は多くの非常によく似た質問を見てきましたので、それを把握することはできません。のpython 3

私はこのような文字列を持っている:

{121{12}12{211}2} 

私が読みたいです

Tree diagram

私は子ノードとして全体のリストを追加するのpythonを伝える方法として混乱しています。このようなツリーに文字列?

また、現在のノードを古いカレントノードの親ノードに変更する方法も知っていますか?ここで

は、これまでの私のコードです:

class Node: 
    def __init__(self,val): 
     self.value = val 
     self.children = [] 
     #init Node class so we can pass in values as nodes and set children to empty list 

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

s=[] 

for i in filedata: 
    if i == leftbrace: 
     n = Node(i) 
    #create new child of current node 
    s = [] 
    #reset list s to blank 

if i == rightbrace: 
    n.add_child(s) 
    #add list s to current node 
    #make parent of current node the new current node 

else: 
    s.append(i) 
    #add i to list s 

for c in n.children: 
    print (c.data) 
+0

クラス定義はどこにありますか? –

+0

あなたはスタックの概念も再帰関数もないようです。ノードに「親」属性を追加し、 'add_child'操作中に初期化することをお勧めします。 –

答えて

1

この作品のようなものを作るためにあなたが再帰を使用する場合、それが最も簡単です。これができる方法の1つがここにあります。

コード:

class Node: 
    def __init__(self, stream): 
     val = [] 
     children = [] 
     while True: 
      try: 
       # get the next character from the stream 
       ch = next(stream) 

       # if this is an open brace, then recurse to a child 
       if ch == '{': 
        children.append(Node(stream)) 

       # if this is a close brace, we are done on this level 
       elif ch == '}': 
        break 

       # otherwise add this character to our value 
       else: 
        val.append(ch) 

      # stream is empty, we are done 
      except StopIteration: 
       break 

     self.value = ''.join(val) 
     self.children = children 

    @classmethod 
    def from_string(cls, string): 
     stream = iter(string) 
     tree_top = Node(stream) 

     # assert that the string started with '{' and was one top node 
     assert len(tree_top.children) == 1 and tree_top.value == '' 
     return tree_top.children[0] 

    def __str__(self): 
     return self.value 

    def __repr__(self): 
     return "Node('%s', <%d children>)" % (
      self.value, len(self.children)) 

    def tree_string(self, level=0): 
     yield '-' + " " * level + str(self) 
     for child in self.children: 
      for child_string in child.tree_string(level+1): 
       yield child_string 

tree = '{121{12}12{211}2}' 
for line in Node.from_string(tree).tree_string(): 
    print(line) 

結果:

-121122 
- 12 
- 211 
+0

ちょっとありがとう、これは私が必要とするものですが、私はまだ__repr__関数を理解する助けが必要です - 私に指し示すことができるチュートリアルはありますか? – Davtho1983

+0

だから、このページの上部にある検索バーに行き、 'python repr'と入力してください。結果ページで、タブをクリックして投票順に並べ替えます。上部はhttp://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python/2626364#2626364です。 –