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