Python 有向无环图中的高效查询
我正在用这些约束构建一个有向无环图(使用python/django)- 图形约束-Python 有向无环图中的高效查询,python,django,data-structures,directed-acyclic-graphs,Python,Django,Data Structures,Directed Acyclic Graphs,我正在用这些约束构建一个有向无环图(使用python/django)- 图形约束- 不允许自链接(父项==子项) 节点不能是它的祖先 自定义约束- 节点的子节点不能是其其他子节点的后代(不允许存在叔叔/婶婶关系)。虽然节点可以是它的表亲(兄弟节点可以和子节点具有相同的节点) 任何节点的最大级别可以是10(级别=节点到根的最短距离) 数据库- 表1(节点)-id、名称 表2(边缘)-标识,父标识(fk), 儿童身份证(fk) 验证- 我正在使用django包来实现这个图,只需稍加修改。这是验证部分
def constraints_checker(parent, child):
"""
Checks all the constraints
"""
parent_ancestors = parent.get_ancestors_set()
if parent == child:
raise ValidationError('Self links are not allowed.')
if child in parent_ancestors:
raise ValidationError('The object is an ancestor.')
# max level validation
root_nodes = parent.get_roots()
for root_node in root_nodes:
if root_node.longest_distance(parent) >= 10:
raise ValidationError('Max. 10 levels allowed.')
# uncle aunt relationship validation
# 1. parent's children's descendents != node
parent_children = parent.children.exclude(id=child.id)
for parent_child in parent_children:
if child in parent_child.get_descendants_set():
raise ValidationError('Uncle/aunt relationship not allowed.')
for ancestor in parent_ancestors:
# 2. ancestor's child != node
if child in ancestor.children.all():
raise ValidationError('Uncle/aunt relationship not allowed.')
我现在用的是寻找祖先和后代。如何优化此图以实现更快的查询
存储左、右标志,以便更快地遍历树。我们能用点什么来画这张图吗
相关,因此回答-