I have a dictionary of a family tree with the name of the child as the key and their dad's and mom's name in a list as the value.
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') }
I need to write a recursive function so that it returns True when there is a descendence between two people. If there is a descendance, it has to print out the chain of relations, i.e:
>>> print("Is there a lineage?", lineage('Amy', 'Kevin', d))
Amy
Alice
Tom
Kevin
Is there a lineage? True
Otherwise if there isn't one:
>>> print("Is there a lineage?", lineage('Mary', 'Alice', d))
Is there a lineage? False
This is what I've got so far. It seems to return True or False consistantly, but I'm having troubles figuring out how to save the path between the two people.
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
I'm new to recursion, so any ideas or help on how to approach this are much appreciated.