# Coding problem 2: The ancestors function below should # return a list of ances
ID: 3776453 • Letter: #
Question
# Coding problem 2: The ancestors function below should
# return a list of ancestors of a person. The list
# is constructed by looking up a person's parents
# in the "parents" dictionary, and then looking up
# those people's parents, etc.
#
# For example:
# >>> ancestors('Mark Zuckerberg')
# ['Edward Zuckerberg', 'Karen Zuckerberg', 'Miriam Holländer', 'Jack Zuckerberg', 'Minnie Wiesenthal', 'Max Zuckerberg']
# >>> ancestors('Edward Zuckerberg')
# ['Miriam Holländer', 'Jack Zuckerberg', 'Minnie Wiesenthal', 'Max Zuckerberg']
# >>> ancestors('Jack Zuckerberg')
# ['Minnie Wiesenthal', 'Max Zuckerberg']
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):
answer = copy(parents.get(person)) # the copy function copies a list
# fill in the rest
Explanation / Answer
Hey in the code given above we might need loop to run untill we find parents() returns null, I could write more clear if the whole code is available, So i will just give idea.If any doubts post comments.
def ancestors(person):
answer=[]
#as long as there are parents for given value, keep storing them.
while copy(parents.get(person)):
answer.append(copy(parents.get(person))
person=copy(parents.get(person)) [0]
#from the list we want one name to get their parent, so placed [0]
return answer
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.