我实际上在学习如何应用递归来解决一些真实的生活问题。比方说,我有一本存放家谱的词典,每个人的孩子都将被存储在这本词典中,并且也存储在树中。我想找出一个家庭的子树并将它存储到一个单独的字典中,所以我必须检查这个人是否有孩子。但是,我不知道为什么递归函数的新字典只能存储那些没有孩子的人。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
你可能想用这个:http://sedimental.org/ remap.html –