我實際上在學習如何應用遞歸來解決一些真實的生活問題。比方說,我有一本存放家譜的詞典,每個人的孩子都將被存儲在這本詞典中,並且也存儲在樹中。我想找出一個家庭的子樹並將它存儲到一個單獨的字典中,所以我必須檢查這個人是否有孩子。但是,我不知道爲什麼遞歸函數的新字典只能存儲那些沒有孩子的人。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 –