【发布时间】:2021-11-27 10:18:53
【问题描述】:
我有一本家谱字典,其中孩子的名字作为键,他们的爸爸和妈妈的名字在列表中作为值。
d = {
'Kevin': ('Tom', 'Marge'),
'Marge': ('John', 'Mary'),
'Elle': ('Tom', 'Marge'),
'Seth': ('Tom', 'Marge'),
'Mary': ('Carl', 'Elena'),
'Tom': ('Joseph', 'Alice'),
'Alice': ('Rob', 'Amy'),
'John': ('James', 'Elena'),
'Joseph': ('Adam', 'Emma'),
'James': ('Nick', 'Maria') }
我需要编写一个递归函数,以便在两个人之间存在下降时返回 True。如果有后代,它必须打印出关系链,即:
>>> print("Is there a lineage?", lineage('Amy', 'Kevin', d))
Amy
Alice
Tom
Kevin
Is there a lineage? True
否则如果没有:
>>> print("Is there a lineage?", lineage('Mary', 'Alice', d))
Is there a lineage? False
这是我到目前为止所得到的。它似乎始终如一地返回 True 或 False,但我在弄清楚如何保存两个人之间的路径时遇到了麻烦。
line = []
def lineage(parent, child, d):
dad, mom = d[child][0], d[child][1]
try:
if parent in d[child]:
line.append(parent)
else:
try:
lineage(parent, dad, d)
except:
lineage(parent, mom, d)
return True
except:
return False
我是递归的新手,因此非常感谢任何有关如何解决此问题的想法或帮助。
【问题讨论】:
标签: dictionary recursion family-tree