networkx 2.8.2 Pypi GitHub Homepage
Other Docs
NotesParametersRaisesYieldsBackRef
topological_sort(G)

A topological sort is a nonunique permutation of the nodes of a directed graph such that an edge from u to v implies that u appears before v in the topological sort order. This ordering is valid only if the graph has no directed cycles.

Notes

This algorithm is based on a description and proof in "Introduction to Algorithms: A Creative Approach" .

Parameters

G : NetworkX digraph

A directed acyclic graph (DAG)

Raises

NetworkXError

Topological sort is defined for directed graphs only. If the graph G is undirected, a NetworkXError is raised.

NetworkXUnfeasible

If G is not a directed acyclic graph (DAG) no topological sort exists and a NetworkXUnfeasible exception is raised. This can also be raised if G is changed while the returned iterator is being processed

RuntimeError

If G is changed while the returned iterator is being processed.

Returns a generator of nodes in topologically sorted order.

Yields

nodes

Yields the nodes in topological sorted order.

See Also

is_directed_acyclic_graph
lexicographical_topological_sort

Examples

To get the reverse order of the topological sort:

>>> DG = nx.DiGraph([(1, 2), (2, 3)])
... list(reversed(list(nx.topological_sort(DG)))) [3, 2, 1]

If your DiGraph naturally has the edges representing tasks/inputs and nodes representing people/processes that initiate tasks, then topological_sort is not quite what you need. You will have to change the tasks to nodes with dependence reflected by edges. The result is a kind of topological sort of the edges. This can be done with networkx.line_graph as follows:

>>> list(nx.topological_sort(nx.line_graph(DG)))
[(1, 2), (2, 3)]
See :

Back References

The following pages refer to to this document either explicitly or contain code examples using this.

networkx.algorithms.dag.topological_sort networkx.algorithms.dag.lexicographical_topological_sort networkx.algorithms.dag.is_directed_acyclic_graph networkx.algorithms.dag.topological_generations

Local connectivity graph

Hover to see nodes names; edges to Self not shown, Caped at 50 nodes.

Using a canvas is more power efficient and can get hundred of nodes ; but does not allow hyperlinks; , arrows or text (beyond on hover)

SVG is more flexible but power hungry; and does not scale well to 50 + nodes.

All aboves nodes referred to, (or are referred from) current nodes; Edges from Self to other have been omitted (or all nodes would be connected to the central node "self" which is not useful). Nodes are colored by the library they belong to, and scaled with the number of references pointing them


GitHub : /networkx/algorithms/dag.py#228
type: <class 'function'>
Commit: