Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for What Is Wrong With This Family? by PythonLearner
from itertools import chain
def is_family(tree):
answer = False
fathers = {}
sons = set()
is_many_fathers = False
for father, son in tree:
if son in sons:
is_many_fathers = True
break
else:
if father not in fathers:
fathers[father] = set()
fathers[father].add(son)
sons.add(son)
if not is_many_fathers:
roots = set(fathers).difference(sons)
if len(roots) == 1:
current_generation = roots
visited = set()
while current_generation and not current_generation.issubset(visited):
visited.update(current_generation)
current_generation_sons = (fathers[father] for father in current_generation if father in fathers)
current_generation = set(chain(*current_generation_sons))
names = sons.union(roots)
answer = visited == names
return answer
June 20, 2018