Python Graphlib Module TopologicalSorter class














































Python Graphlib Module TopologicalSorter class



         ***** Topologicalsorter class *****

class graphlib.TopologicalSorter(graph=None)
      -provides functionality to topologically sort a     group of Hashable nodes.



Topological sorting when Graph is initialised:

 If the optional graph argument is provided it must be a dictionary representing a directed cyclic graph where the keys are nodes and the values are iterables of all predecessors of that node in the graph.

Example
import graphlib

graph = {1 : {6},2: {3}, 3: {1}, 4: {0, 1}, 5: {0, 2}}
  

ts = graphlib.TopologicalSorter(graph)
  

print([*ts.static_order()])


output:
[6, 0, 1, 3, 4, 2, 5]


TOPOLOGICAL SORTING WHEN GRAPH IS unINITIALISED:

To add a new node to the graph use add(node*predecessors)


from graphlib import TopologicalSorter
  

ts = TopologicalSorter()
  

ts.add(3, 2, 1)

ts.add(1, 0)
  

print([*ts.static_order()])


output

[2, 0, 1, 3]





The particular order that is returned may depend on the specific order in which the items were inserted in the graph.
For example
:

from graphlib import TopologicalSorter
  

ts = TopologicalSorter()

ts.add(1,0) 

ts.add(3, 2, 1)


print([*ts.static_order()])

output:

[0, 2, 1, 3]




Here, 0 and 2 are at the same level
















Comments