PYTHON The parents dictionary in the final.py file is a dictionary whose keys ar
ID: 3859237 • Letter: P
Question
PYTHON
The parents dictionary in the final.py file is a dictionary whose keys are strings (names) and whose values are lists of strings (names). For example:
The parents of Mark Zuckerberg (the CEO of Facebook) are named Edward Zuckerberg and Karen Zuckerberg.
Complete the ancestors function, so that it returns a list of the ancestors of a person, including the person's parents, grandparents, great grandparents, and so on (assuming those ancestors are listed in the dictionary). Although the parents dictionary as it stands only goes back as far as two of Mark's great grandparents, you should assume that the ancestry information of a person might continue for an arbitrary number of generations.
When completed, here are some of examples of correct output:
CODE GIVEN: (Must just fill in code that is given! Question is above!)
parents = dict()
parents['Mark Zuckerberg'] = ['Edward Zuckerberg', 'Karen Zuckerberg']
parents['Edward Zuckerberg'] = ['Miriam Holländer', 'Jack Zuckerberg']
parents['Jack Zuckerberg'] = ['Minnie Wiesenthal', 'Max Zuckerberg']
def ancestors(person):
# base case
if parents.get(person) == None:
# you should return something here
pass
# recursive case
else:
ancs = parents.get(person)
# fill in the rest
# return something at the end
Explanation / Answer
parents = dict()
parents['Mark Zuckerberg'] = ['Edward Zuckerberg', 'Karen Zuckerberg']
parents['Edward Zuckerberg'] = ['Miriam Hollander', 'Jack Zuckerberg']
parents['Jack Zuckerberg'] = ['Minnie Wiesenthal', 'Max Zuckerberg']
tmp_list = []
def ancestors(person,tmp_list):
# base case
if parents.get(person) == None:
# you should return something here
pass
# recursive case
else:
ancs = parents.get(person)
tmp_list.append(ancs)
for val in ancs:
ancestors(val,tmp_list)
# fill in the rest
# return something at the end
#ancestors('Mark Zuckerberg', tmp_list)
#ancestors('Edward Zuckerberg', tmp_list)
ancestors('Jack Zuckerberg', tmp_list)
print(tmp_list)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.