2017-09-27 51 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