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 kazuki.h
from collections import deque
def is_family(tree):
me = tree[0][0]
q, switch_dict = deque([me]), {me: 0}
while q:
q0 = q.pop()
switch = switch_dict[q0]
father_list = [father for father, son in tree if son == q0]
if len(father_list) > 1: return False
elif len(father_list) == 1:
father = father_list[0]
if father in switch_dict.keys():
if switch_dict[father] != switch-1: return False
else:
switch_dict[father] = switch-1
q.append(father)
for son in [son for father, son in tree if father == q0]:
if son in switch_dict.keys():
if switch_dict[son] != switch+1: return False
else:
switch_dict[son] = switch+1
q.append(son)
len({m for m, _ in tree}|{m for _, m in tree}) == len(switch_dict.keys())
return len({m for m, _ in tree}|{m for _, m in tree}) == len(switch_dict.keys())
Dec. 18, 2021