所以我们有一个关于家庭的词典,谁是谁的孩子。 (这是一个全局变量)
kids= {
"Adam": ["Matjaž", "Cilka", "Daniel"],
"Aleksander": [],
"Alenka": [],
"Barbara": [],
"Cilka": [],
"Daniel": ["Elizabeta", "Hans"],
"Erik": [],
"Elizabeta": ["Ludvik", "Jurij", "Barbara"],
"Franc": [],
"Herman": ["Margareta"],
"Hans": ["Herman", "Erik"],
"Jožef": ["Alenka", "Aleksander", "Petra"],
"Jurij": ["Franc", "Jožef"],
"Ludvik": [],
"Margareta": [],
"Matjaž": ["Viljem"],
"Petra": [],
"Tadeja": [],
"Viljem": ["Tadeja"],
}
现在我们有一个递归函数:
def richest(person, money):
金钱是一个本地变量,具有每个人的金额。
money = {
"Adam": 42,
"Aleksander": 3,
"Alenka": 3,
"Barbara": 37,
"Cilka": 242,
"Daniel": 4,
"Erik": 32,
"Elizabeta": 8,
"Franc": 16,
"Herman": 12,
"Hans": 55,
"Jožef": 7,
"Jurij": 5,
"Ludvik": 37,
"Margareta": 20,
"Matjaž": 142,
"Petra": 3,
"Tadeja": 45,
"Viljem": 55
}
当我调用函数richest("Elizabeta", money)
时,它应该返回最大金额和金额的人。
在这种情况下,将返回:[("Ludvik", 37), ("Barbara", 37)]
我试图制作一个递归函数,但它无法正常工作。
def richest(person, money):
people=[]
for kid in kids[person]:
#goes for each kid of that person and their kids.
return #somehow append it into the people array
如果有人帮助我,我做错了什么?我也尝试过使用生成器,但是它会在每个孩子中加上[None],所以它也不起作用..
答案 0 :(得分:0)
def richest(person, money):
for kid in kids[person]:
money = richest(kid, money) + money
return money[person]
people=[]
for person in kid:
people.append(person, richest(person, money[person]))
你必须让人员列表在递归之外,否则没有意义将这个人追加到一个列表,其范围是一个函数,其参数是一个人,如果你愿意,那么它必须有的人列表作为参数
答案 1 :(得分:0)
这是以递归方式解决问题的函数:
def richest(person, money):
people = [(person, money[person])]
for child in kids[person]:
# Recursively find the richest descendants of this child (including this child)
descendants = richest(child, money)
# Merge with currently found richest people in the branch
if descendants:
if descendants[0][1] > people[0][1]:
# Descendants are the new richest people
people = descendants
elif descendants[0][1] == people[0][1]:
# Descendants are as rich as previosly found richest people
people += descendants
return people
(我们仅比较列表descendants
和people
中第一个人的钱,因为两个列表中的所有人都同样富有。)