Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Fall from the tree solution in Creative category for What Is Wrong With This Family? by alterGNU
def oldest(dico):
"""
Return the oldest family member
"""
start = list(dico.values())[0]
while start in dico:
start = dico.get(start)
return start
def next_gen(dico,gen):
"""
dict()*set()->set()
take a set of name of generation N (parents) --return-> set of name of the next generation (N+1) (childs)
"""
new_gen, old_gen=set(), set()
for p in gen:
old_gen.add(p)
for e in dico:
if dico[e] == p:
new_gen.add(e)
return (gen | new_gen) - old_gen
def is_family(tree):
dico={} # dict {son:dad}
# dico construction
for p in tree:
if not(p[1] in dico):
if (dico.get(p[0],"") != p[1]):
dico[p[1]]=p[0]
else:
return False # Can't be you father's father
else:
return False # Can't have two fathers (well...that's a bit of a touchy subject...!)
# Good news everyone...
everyone=set(dico) | set(dico.values())
racine=oldest(dico)
parents = set() # init parents to the top: Racine, the oldest one.
parents.add(racine)
while parents != set(): # Falling of the tree
parents=next_gen(dico,parents)
for d in parents:
everyone.remove(d)
everyone.remove(racine) # remove The elder
return (everyone == set()) # if it's an ok_family: everyone should be empty now.
if __name__ == "__main__":
#These "asserts" using only for self-checking and not necessary for auto-testing
assert is_family([
['Logan', 'Mike']
]) == True, 'One father, one son'
assert is_family([
['Logan', 'Mike'],
['Logan', 'Jack']
]) == True, 'Two sons'
assert is_family([
['Logan', 'Mike'],
['Logan', 'Jack'],
['Mike', 'Alexander']
]) == True, 'Grandfather'
assert is_family([
['Logan', 'Mike'],
['Logan', 'Jack'],
['Mike', 'Logan']
]) == False, 'Can you be a father to your father?'
assert is_family([
['Logan', 'Mike'],
['Logan', 'Jack'],
['Mike', 'Jack']
]) == False, 'Can you be a father to your brother?'
assert is_family([
['Logan', 'William'],
['Logan', 'Jack'],
['Mike', 'Alexander']
]) == False, 'Looks like Mike is stranger in Logan\'s family'
assert is_family([
['Jack', 'Mike'],
['Logan', 'Mike'],
['Logan', 'Jack'],
]) == False, 'Two fathers'
print("Looks like you know everything. It is time for 'Check'!")
May 21, 2021