# Single Gold Star # Family Trees # In the lecture, we showed a recursive definition for your ancestors. For this # question, your goal is to define a procedure that finds someone's ancestors, # given a Dictionary that provides the parent relationships. # Here's an example of an input Dictionary: ada_family = { 'Judith Blunt-Lytton': ['Anne Isabella Blunt', 'Wilfrid Scawen Blunt'], 'Ada King-Milbanke': ['Ralph King-Milbanke', 'Fanny Heriot'], 'Ralph King-Milbanke': ['Augusta Ada King', 'William King-Noel'], 'Anne Isabella Blunt': ['Augusta Ada King', 'William King-Noel'], 'Byron King-Noel': ['Augusta Ada King', 'William King-Noel'], 'Augusta Ada King': ['Anne Isabella Milbanke', 'George Gordon Byron'], 'George Gordon Byron': ['Catherine Gordon', 'Captain John Byron'], 'John Byron': ['Vice-Admiral John Byron', 'Sophia Trevannion'] } # Define a procedure, ancestors(genealogy, person), that takes as its first input # a Dictionary in the form given above, and as its second input the name of a # person. It should return a list giving all the known ancestors of the input # person (this should be the empty list if there are none). The order of the list # does not matter and duplicates will be ignored. def ancestors(genealogy, person): list_of_ancestors=[] if person in genealogy: list_of_ancestors=genealogy[person] for e in genealogy[person]: for i in ancestors(genealogy,e): if i not in list_of_ancestors: list_of_ancestors+=ancestors(genealogy,e) else: list_of_ancestors+=[] return list_of_ancestors # Here are some examples: print ancestors(ada_family, 'Augusta Ada King') #>>> ['Anne Isabella Milbanke', 'George Gordon Byron', # 'Catherine Gordon','Captain John Byron'] print ancestors(ada_family, 'Judith Blunt-Lytton') #>>> ['Anne Isabella Blunt', 'Wilfrid Scawen Blunt', 'Augusta Ada King', # 'William King-Noel', 'Anne Isabella Milbanke', 'George Gordon Byron', # 'Catherine Gordon', 'Captain John Byron'] print ancestors(ada_family, 'Dave') #>>> []
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question