add method of topologicalsorter in Python

The add() method adds a node and its predecessors to the graph. The graph should be a DAG for the sorting to work.

Topologicalsorter Updated 23 Jul 2021 1 min read

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

python
# 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

Output
DAG in linear order:

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