如何做一个递归函数来获得一个家庭的最大收入?

2024-06-16 10:36:42 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我们有一个家庭和谁是谁的孩子的口述。(这是一个全局变量)

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

我做错了什么有人能帮我吗?我也尝试了一些发电机,但它附加[并没有]到每个孩子,所以它不工作太。。你知道吗


Tags: kidspersondanielmoneyerikfranchansbarbara
2条回答
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]))

必须将人员列表置于递归之外,否则将人员附加到其作用域为参数为人员的函数的列表(如果需要)是没有意义的,而必须将人员列表作为参数

下面是递归解决问题的函数:

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

(我们只比较列表descendantspeople中第一个人的钱,因为两个列表中的所有人都同样富有。)

相关问题 更多 >