13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

创新互联Python教程:graphlib —- 操作类似图的结构的功能

graphlib —- 操作类似图的结构的功能

源代码: Lib/graphlib.py


class graphlib.TopologicalSorter(graph=None)

提供以拓扑方式对可哈希节点的图进行排序的功能。

拓扑排序是指图中顶点的线性排序,使得对于每条从顶点 u 到顶点 v 的有向边 u -> v,顶点 u 都排在顶点 v 之前。 例如,图的顶点可以代表要执行的任务,而边代表某一个任务必须在另一个任务之前执行的约束条件;在这个例子中,拓扑排序只是任务的有效序列。 完全拓扑排序 当且仅当图不包含有向环,也就是说为有向无环图时,完全拓扑排序才是可能的。

如果提供了可选的 graph 参数则它必须为一个表示有向无环图的字典,其中的键为节点而值为包含图中该节点的所有上级节点(即具有指向键中的值的边的节点)的可迭代对象。 额外的节点可以使用 add() 方法添加到图中。

在通常情况下,对给定的图执行排序所需的步骤如下:

  • 通过可选的初始图创建一个 TopologicalSorter 的实例。

  • 添加额外的节点到图中。

  • 在图上调用 prepare()。

  • 当 is_active() 为 True 时,迭代 get_ready() 所返回的节点并加以处理。 完成处理后在每个节点上调用 done()。

在只需要对图中的节点进行立即排序并且不涉及并行性的情况下,可以直接使用便捷方法 TopologicalSorter.static_order():

 
 
 
 
  1. >>> graph = {"D": {"B", "C"}, "C": {"A"}, "B": {"A"}}
  2. >>> ts = TopologicalSorter(graph)
  3. >>> tuple(ts.static_order())
  4. ('A', 'C', 'B', 'D')

这个类被设计用来在节点就绪时方便地支持对其并行处理。 例如:

 
 
 
 
  1. topological_sorter = TopologicalSorter()
  2. # Add nodes to 'topological_sorter'...
  3. topological_sorter.prepare()
  4. while topological_sorter.is_active():
  5. for node in topological_sorter.get_ready():
  6. # Worker threads or processes take nodes to work on off the
  7. # 'task_queue' queue.
  8. task_queue.put(node)
  9. # When the work for a node is done, workers put the node in
  10. # 'finalized_tasks_queue' so we can get more nodes to work on.
  11. # The definition of 'is_active()' guarantees that, at this point, at
  12. # least one node has been placed on 'task_queue' that hasn't yet
  13. # been passed to 'done()', so this blocking 'get()' must (eventually)
  14. # succeed. After calling 'done()', we loop back to call 'get_ready()'
  15. # again, so put newly freed nodes on 'task_queue' as soon as
  16. # logically possible.
  17. node = finalized_tasks_queue.get()
  18. topological_sorter.done(node)

3.9 新版功能.

异常

graphlib 模块定义了以下异常类:

exception graphlib.CycleError

ValueError 的子类,当特定的图中存在环时将由 TopologicalSorter.prepare() 引发。 如果存在多个环,则将只报告其中一个未定义的选项并将其包括在异常中。

检测到的环可以通过异常实例的 args 属性的第二个元素来访问,它由一个节点列表组成,其中的每个节点在图中都是列表中下一个节点的直接上级节点。 在报告的列表中,开头和末尾的节点将是同一对象,以表明它是一个环。


名称栏目:创新互联Python教程:graphlib —- 操作类似图的结构的功能
网页网址:http://cdbrznjsb.com/article/dpsoces.html

其他资讯

让你的专属顾问为你服务