我有一個家譜字典,以孩子的名字為鍵,以串列中的父親和媽媽的名字為值。
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
我是遞回的新手,因此非常感謝有關如何解決此問題的任何想法或幫助。
uj5u.com熱心網友回復:
True當路徑存在時,我讓您的函式回傳路徑,而不是。- 我建議避免
try / except在這里。
確實,嘗試訪問d[child]而不檢查其中的child內容d可能會導致例外。但是,這是遞回的基本情況;如果基本情況if在函式的開頭用顯式明確標識,而不是在函式末尾沒有解釋的晦澀的“發生了一些例外”,那么您的代碼將更容易理解。
def lineage(parent, child, d):
if parent == child:
return [child]
elif child not in d:
return False
else:
dad, mom = d[child][0], d[child][1]
path_via_dad = lineage(parent, dad, d)
if path_via_dad:
path_via_dad.append(child)
return path_via_dad
else:
path_via_mom = lineage(parent, mom, d)
if path_via_mom:
path_via_mom.append(child)
return path_via_mom
else:
return False
這是一個更短的等效版本,它依賴or于 python中邏輯運算子的特定行為:
def lineage(parent, child, d):
if parent == child:
return [child]
elif child not in d:
return False
else:
dad, mom = d[child][0], d[child][1]
path = lineage(parent, dad, d) or lineage(parent, mom, d)
if path:
path.append(child)
return path
測驗:
>>> lineage('Amy', 'Kevin', d)
['Amy', 'Alice', 'Tom', 'Kevin']
>>> lineage('Mary', 'Alice', d)
False
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375122.html
