使用 graphlib Python模块进行拓扑排序
拓扑排序是有向无环图顶点的线性排序。对于每个有向边 uv,顶点 u 在拓扑排序中排在 v 之前。
Python 3.9.0 中引入的Python模块 graphlib 给出了图的拓扑排序,其中图在字典中表示。假设图没有平行边,图可以用字典表示,顶点为键,值是它们连接的节点。
要安装此模块,请在终端中运行此命令。
pip install graphlib
我们将使用类graphlib。 TopologicalSorter(graph= None) ,以及带有 TopologicalSorter 实例的以下函数:
add( node, *predecessors ):
Adds a new node and it’s dependencies to a graph. For example, ts.add(3, 2, 1) adds key value 3 and it’s predecessors 2, 1 to the graph.
static_order():
Returns an iterable of nodes in a topological order.
检查下面的程序以使用 graphlib.TopologicalSorter() 进行拓扑排序
示例 1:使用 TopologicalSorter 进行拓扑排序,图形未初始化。
Python3
# Python 3.9.0 program for
# topological sorting using
# graphlib module
from graphlib import TopologicalSorter
# creating an instance of TopologicalSorter
# initial graph is optional
ts = TopologicalSorter()
# adding vertex and it's nodes
ts.add(3, 2, 1)
# adding more node and predecessor
ts.add(1, 0)
# printing the topological order
# returned by static_order()
print([*ts.static_order()])
Python3
# Python program for topological sorting
# through graphlib module
from graphlib import TopologicalSorter
# making graph
graph = {2: {3}, 3: {1}, 4: {0, 1}, 5: {0, 2}}
# creating an instance of TopolocialSorter
# with initial graph(initial graph is optional)
ts = TopologicalSorter(graph)
# printing the topological order
# returned by static_order()
print([*ts.static_order()])
输出:
[2, 0, 1, 3]
示例 2:使用 TopologicalSorter 使用初始化的图进行拓扑排序。
蟒蛇3
# Python program for topological sorting
# through graphlib module
from graphlib import TopologicalSorter
# making graph
graph = {2: {3}, 3: {1}, 4: {0, 1}, 5: {0, 2}}
# creating an instance of TopolocialSorter
# with initial graph(initial graph is optional)
ts = TopologicalSorter(graph)
# printing the topological order
# returned by static_order()
print([*ts.static_order()])
输出:
[1, 0, 3, 4, 2, 5]