Easy Tutorial
❮ Python Os Fchdir Python Os Popen ❯

Python Topological Sorting

Python3 Examples

Topological sorting for a Directed Acyclic Graph (DAG) G is a linear ordering of its vertices such that for every directed edge (u, v), vertex u comes before v in the ordering. This linear sequence is called a topological order if it satisfies the topological sequence condition. In simple terms, topological sorting is the process of obtaining a total order from a partial order on a set.

In graph theory, a sequence of vertices in a directed acyclic graph is considered a topological sort (English: Topological sorting) if and only if the following conditions are met:

Example

from collections import defaultdict 

class Graph: 
    def __init__(self,vertices): 
        self.graph = defaultdict(list) 
        self.V = vertices

    def addEdge(self,u,v): 
        self.graph[u].append(v) 

    def topologicalSortUtil(self,v,visited,stack): 

        visited[v] = True

        for i in self.graph[v]: 
            if visited[i] == False: 
                self.topologicalSortUtil(i,visited,stack) 

        stack.insert(0,v) 

    def topologicalSort(self): 
        visited = [False]*self.V 
        stack =[] 

        for i in range(self.V): 
            if visited[i] == False: 
                self.topologicalSortUtil(i,visited,stack) 

        print (stack) 

g= Graph(6) 
g.addEdge(5, 2); 
g.addEdge(5, 0); 
g.addEdge(4, 0); 
g.addEdge(4, 1); 
g.addEdge(2, 3); 
g.addEdge(3, 1); 

print ("Topological Sort Result:")
g.topologicalSort()

Executing the above code produces the following output:

Topological Sort Result:
[5, 4, 2, 3, 1, 0]

Python3 Examples

❮ Python Os Fchdir Python Os Popen ❯