所以我们有一个家庭和谁是谁的孩子的口述。(这是一个全局变量)
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)
时,它应该返回带有max money和money数量的person/s。
在本例中,返回:[("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
我做错了什么有人能帮我吗?我也尝试了一些发电机,但它附加[并没有]到每个孩子,所以它不工作太。。你知道吗
必须将人员列表置于递归之外,否则将人员附加到其作用域为参数为人员的函数的列表(如果需要)是没有意义的,而必须将人员列表作为参数
下面是递归解决问题的函数:
(我们只比较列表
descendants
和people
中第一个人的钱,因为两个列表中的所有人都同样富有。)相关问题 更多 >
编程相关推荐