gpt4 book ai didi

python - 如何在 python 字典中保持循环以搜索值?

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:05 24 4
gpt4 key购买 nike

parent = {'Amy':'Ben', 'May':'Tom', 'Tom':'Ben',
'Ben':'Howard', 'Howard':'George', 'Frank':'Amy',
'Joe':'Bill', 'Bill':'Mary', 'Mary':'Philip', 'Simon':'Bill',
'Zoe':'Mary'}

这是问题中提到的父字典。我的任务是:

判断输入的2个名字是否是祖先。例如,Amy 的 parent 是 Ben,Ben 的 parent 是 Howard,因此 Howard 和 Amy 是祖先关系。

下面是我的代码:

    def is_ancestor(name1,name2,pdict):
for name in pdict:
parent = pdict.get(name2)
parent2 = pdict.get(parent)
if(name1 == parent2):
return True
else:
return False

这适用于我上面提到的示例案例。但是,如果问题是“Amy”和“Howard”怎么办?它应该返回 True,因为“Amy”的父级是“Tom”,Tom 的父级是 Ben,而 Ben 的父级是 Howard。所以艾米和霍华德是祖宗。但是我的代码会在得到 tom 和 ben 之后停止。如何让它一直循环直到我找到正确答案?

下面是确切的问题:

Person A is an (indirect) ancestor of Person B if Person B is considered to be one of the many descendants of Person A.

In the example ancestry tree given above, Howard is an ancestor of Amy, but Amy is not an ancestor of Tom.

And that person himself is NOT his own ancestor. Your task is to write a function,
is_ancestor(name1,name2,pdict), that takes in three arguments.

The first two arguments are the names of people (strings), while the third argument is
the parent dictionary mentioned above.

The function should return the boolean value ‘True’ if the first person in the argument list is an ancestor of the second person,

and ‘False’ if the first person in the argument list is not an
ancestor of the second person.

最佳答案

这是你使用递归的答案:

def is_ancestor(name1, name2, pdict):

try:
if pdict[name1] == name2:
return True
else:
return is_ancestor(pdict[name1], name2, pdict)
except KeyError:
return False

首先它会检查它是否找到了直接祖先,如果没有,则通过递归相同的函数来检查下一代。如果未找到祖先,则会触发 KeyError 异常,表明 name2 不是 name1 的祖先。

关于python - 如何在 python 字典中保持循环以搜索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58285723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com