I have a graph G in networkx and would like to sort the nodes according to their degree. However, the following code does not work in latest networkx versions:
sorted(set(G.degree().values()))
and the following seems a bit clunky as it requires converting the networkx DegreeView to a python list of tuples
degrees = [(node,val) for (node, val) in G.degree()]
sorted(degrees, key=lambda x: x[1], reverse=True)
is there any better way?
There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges).
We print the nodes which have not been visited (nodes that have degree >= 2) as the nodes forming the cycle in the graph. If all vertices have been visited, there is no cycle in the graph. An undirected graph has only 1 vertex whose degree is 2.
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.
The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges). In DFS, we print a vertex and then recursively call DFS for its adjacent vertices.
The following works:
sorted(G.degree, key=lambda x: x[1], reverse=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With