Cycles · Acyclic Graphs

Lesson 8

Nikolai Chukhin · Alexander S. Kulikov

In Python, there are built-in methods for finding a topological ordering.

import networkx as nx

graph = nx.DiGraph([(2, 1), (1, 5), (5, 4), (2, 5), (1, 3)])

if nx.is_directed_acyclic_graph(graph):
   print('Topological ordering:', *nx.topological_sort(graph))
else:
   print('The graph is cyclic, so it cannot be topologically sorted.')

Topological ordering: 2 1 5 3 4