2016-10-17 12 views
0

を使用してバイナリツリー、印刷すべてのルート・ツー・葉のパスを考えると、私はscipyのダウンロードからhierarchy.to_treeを使用している、と私はすべてのルート・ツー・葉のパスのプリントアウトを得ることに興味がある:はscipyのダウンロード

enter image description here

10.8.3 10.8.5 10.2.2

from scipy.cluster import hierarchy 
a = hierarchy.to_tree(linkage_matrix) 

私はそれを試す与えてくれた

linkage_matrix 
[[2, 3, 0.06571365, 2], [0, 10, 0.07951425, 2], [5, 6, 0.09405724, 2], [11, 13, 0.10182075, 3], [1, 12, 0.12900146, 3], [14, 15, 0.13498948, 5], [8, 9, 0.16806049, 2], [7, 16, 0.1887918, 4], [17, 19, 0.2236683, 9], [18, 20, 0.29471335, 11], [4, 21, 0.45878, 12]] 

from scipy.cluster import hierarchy 
a = hierarchy.to_tree(linkage_matrix) 

def parse_tree(tree, path): 
    path = path 
    if path ==[]: 
     path.append(str(tree.get_id())) 
    if tree.is_leaf() is False: 
     left = tree.get_left() 
     left_id = str(left.get_id()) 
     if left.is_leaf() is False: 
      path.append(left_id) 
      parse_tree(left, path) 
      path.pop() 
     else: 
      parse_tree(left, path) 
     right = tree.get_right() 
     right_id = str(right.get_id()) 
     if right.is_leaf() is False: 
      path.append(right_id) 
     parse_tree(right, path) 
    else: 
     path.append(str(tree.get_id())) 
     print(('.').join(path)) 
     path.pop() 

parse_tree(a, []) 

しかし、明らかに私のロジックは完全に間違っています。具体的には、左ノードが休暇ではないときに故障します(22.21.20.17.15.19.7は22.21.20.19.7でなければなりません)。私は新しい方法を探していますが、私は考慮しませんでした。以下の例ツリーの

、すべてのルート・ツー・葉のパスは以下のとおりです。

答えて

3

あなたのコードを見ずに、あなたは次のように何かをする必要があります。今、あなたのコードを見た

print_paths(tree, seen): 
    seen = seen 
    seen.append(tree.value) 
    if not tree.children: 
     print(seen) 
    else: 
     map(print_paths, tree.children) 

、してみてください何かのように:それに打撃を与えるための

def parse(tree, p): 
    path = p[:] 
    path.append(str(tree.get_id())) 
    if tree.is_leaf(): 
     print('.'.join(path)) 
    else: 
     #Here I assume get_left() returns some falsey value for no left child 
     left = tree.get_left() 
     if left: 
      parse(left, path) 
     right = tree.get_right() 
     if right: 
      parse(right, path) 
+0

おかげで、これは同様の方法で壊れる: >>>パース([]) 22.4 22.4.21.18.8 22.4.21.18.8.9 –

+0

多分問題は、参照渡しのリストです。 'path = path'を' path = p [:] 'に変更しました。ここで' p'は引数です –

+0

ああ私の神!私はこれがうまくいくと思います。p [:]は正確に何をしていますか?このトピックについて読むことができるリンクはありますか? –

関連する問題