Add Method Of Topologicalsorter In Python

Overview:

  • The add() method adds a node to the graph in a TopologicalSorter object.
  • The predecessors to the nodes are specified next to the node parameter.
  • The nodes and predecessors could be integers, floating point numbers, Python objects or a combination of them. For example, one node could be an integer and another node could be a Python string.
  • Once all the nodes of a DAG is added the method static_order() can be called to get the linear order of the nodes. 

Example:

# Example Python program that constructs a 
# Directed Acyclic Graph using the
# add() method of class TopologicalSorter
import graphlib

# Create a TopologicalSorter object
vertexSorter = graphlib.TopologicalSorter()

# Add nodes to the DAG
vertexSorter.add("C", "B")
vertexSorter.add("B", "A")
vertexSorter.add("D", "B")
vertexSorter.add("E", "B")

# Sort the vertices in topological order
vertexSet = tuple(vertexSorter.static_order())
print("DAG in linear order:");
print(vertexSet)

Output:

DAG in linear order:

('A', 'B', 'C', 'D', 'E')

 


Copyright 2023 © pythontic.com