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 tokiojapan55
class Family:
class Node:
def __init__(self, parent=None, name=None, children=[]):
self.parent = parent
self.name = name
self.children = children
def add_child(self, name):
self.children.append(Family.Node(self, name, []))
def __init__(self, parent=None, child=None):
if parent==None or child==None:
self.root = None
else:
self.root = Family.Node(None, parent, [])
self.root.add_child(child)
def search(self, name):
def _find(root, name):
if root:
if root.name==name:
return root
for node in root.children:
result = _find(node, name)
if result:
return result
return None
return _find(self.root, name)
def is_empty(self):
return self.root==None
def add_ancestor(self, name):
self.root = Family.Node(None, name, [self.root])
def is_family(tree):
family,pending = Family(),list()
loop = True
while loop:
loop = False
pending = list()
for parent,child in tree:
p_node,c_node = family.search(parent),family.search(child)
if not p_node and not c_node:
if family.is_empty():
family = Family(parent, child)
loop = True
else:
pending.append([parent, child])
elif p_node and c_node:
if not c_node.parent or c_node.parent.name!=parent:
return False
elif p_node:
p_node.add_child(child)
loop = True
elif c_node.parent:
return False
else:
family.add_ancestor(parent)
loop = True
if loop:
tree,pending = pending,list()
return pending==list()
June 23, 2020
Comments: