Python question(coding problem) ! Help me. Please make sure that your code works
ID: 3775952 • Letter: P
Question
Python question(coding problem) ! Help me.
Please make sure that your code works in the .py file. I copied the template, so you can copy it to your py file.
Here is the template, copy below:
from random import randint
from tkinter import *
from tkinter.messagebox import showinfo
from urllib.request import urlopen
from urllib.parse import urljoin
from html.parser import HTMLParser
from copy import copy
# 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
from copy import copy
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
print(answer)
# fill in the rest
for x in answer: # we irerating over all elemnt in answer(all ancestors to ancestors)
if x in parents: #checking for a ancestors has another ancestors
answer+=parents[x] #adding ancestors to list
return answer
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.