Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
find_root solution in Clear category for What Is Wrong With This Family? by pokosasa
def is_family(tree):
def find_root(person):
if parent[person]==person:
return person
return find_root(parent[person])
parent={}
for father,son in tree:
parent[father]=father
parent[son]=son
for father,son in tree:
if parent[son]!=son:
return False
if find_root(son)==find_root(father):
return False
parent[son]=father
return sum(father==son for son,father in parent.items())==1
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 for your father?'
assert is_family([
['Logan', 'Mike'],
['Logan', 'Jack'],
['Mike', 'Jack']
]) == False, 'Can you be a father for your brather?'
assert is_family([
['Logan', 'William'],
['Logan', 'Jack'],
['Mike', 'Alexander']
]) == False, 'Looks like Mike is stranger in Logan\'s family'
print("Looks like you know everything. It is time for 'Check'!")
Nov. 23, 2019