Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find nodes with no outgoing edges in networkx?

I am trying to find nodes with no outgoing edges in a digraph in networkx.

Is there a way to do this? I found isolates but that finds edges without incoming or outgoing edges, and I don't want that.

like image 511
Jason S Avatar asked Aug 13 '17 05:08

Jason S


People also ask

What is Nbunch in NetworkX?

nbunch. An nbunch is a single node, container of nodes or None (representing all nodes). It can be a list, set, graph, etc.. To filter an nbunch so that only nodes actually in G appear, use G.

How can you tell if a graph is directed by NetworkX?

To check if the graph is directed you can use nx. is_directed(G) , you can find the documentation here. 'weight' in G[1][2] # Returns true if an attribute called weight exists in the edge connecting nodes 1 and 2.

What is a DiGraph in NetworkX?

A DiGraph stores nodes and edges with optional data, or attributes. DiGraphs hold directed edges. Self loops are allowed but multiple (parallel) edges are not. Nodes can be arbitrary (hashable) Python objects with optional key/value attributes.


2 Answers

If G is your DiGraph, you can get an iterator of sinks through

(node for node, out_degree in G.out_degree_iter() if out_degree == 0)
like image 194
fuglede Avatar answered Oct 08 '22 01:10

fuglede


"methods that returned an iterator have been removed"

in NetworkX 2.x, so @fuglede's answer needs a minor update:

(node for node, out_degree in G.out_degree() if out_degree == 0)

The view/reporting API provided by .out_degree in 2.x provides an OutDegreeView over (node, out_degree) pairs, making this approach slightly simpler than @Fony Lew's.

like image 33
Chris Keefe Avatar answered Oct 08 '22 01:10

Chris Keefe