2017-09-27 12 views
1

実際の生活の問題を解決するために再帰を適用する方法を実際に学習しています。たとえば、私は家系図を保存している辞書を持っており、各人の子供はこの辞書にもその階層にも格納されます。私は家族のサブツリーを見つけてそれを別の辞書に保存したいので、この人に子供がいるかどうかをチェックしなければなりません。しかし、なぜ私の再帰関数の新しい辞書は子供を持たない人々だけを保存できるのか分かりません。私の再帰関数の新しい辞書は、人だけを保存することができますなぜPythonは再帰的に親の息子を見つける

dict[1] = [[2,3], 2] #the first one is the children list, the second one is the level in the family tree 

newDict = {} 
subtree = findSub(dict, 2, 0, newDict) 

#my newDict is an empty dictionary, newDict= {} 
#level stores the person's level in the tree 
def findSub(dict, parent, level, newDict): 

    level += 1 

    children = dict[parent][0] 

    if (len(children) == 0): 
     info = [dict[parent][0], level] 
     newDict[parent] = info 

    else: 
     for child in children: 
      findSub(dict, child, level, newDict) 

    return newDict 
+0

ような何かをするだろうあなたは、おそらくこの使用する:http://sedimental.org/をremap.html –

答えて

1

しかし、私はが子を持っていないことを知りません。

def findSub(dict, parent, level, newDict): 

    level += 1 

    children = dict[parent][0] 

    if (len(children) == 0): 
    ^^^^^^^^^^^^^^^^^^^^^^^^ 
     info = [dict[parent][0], level] 
    ..... 

要素に子がない場合は、このifチェック。子供がいる場合、あなたはさらに再発しますが、さらに再帰する前に要素を追加しません。

あなたは(最終的には全体のサブツリーになります)も、両親を保存したい場合は、

def findSub(dict, parent, level, newDict): 

    level += 1 

    children = dict[parent][0] 
    info = [dict[parent][0], level] 
    newDict[parent] = info 

    if (len(children) != 0): 
     for child in children: 
      findSub(dict, child, level, newDict) 

    return newDict 
+0

ああ、うまくいきます。私は本当に再帰関数の概念をどのように習得できるのかを知りたい。 – androidnewbie

+1

私はスタックとそのメカニック(関数がどのようにスタックに入れられ、実行後にそこから削除されるか)を学ぶことができました:http://interactivepython.org/runestone/static/pythonds/Recursion/StackFramesImplementingRecursion.html – Igor

関連する問題