简体   繁体   中英

How to efficiently get output nodes in a directed graph in networkx?

I created a simple directed graph (DiGraph) in the Python network package networkx , like so:

import networkx as nx

G = DiGraph([(1, 2)])

Now I would like to know the fastest / most efficient way to determine the output nodes (which in this case is the node 2). By output node I mean nodes in the directed graph that have no successor - with input nodes being nodes that have no predecessor. The analogy is from Machine Learning, in which I am supplying values to the input nodes, perform mathematical operations on the edges and have output values in the output nodes . See here for an example, in which p, d and lambda are input nodes and p' and d' are output nodes.

After reading the documentation I came up with such inefficient methods as traversing all nodes of the graph, calling successors() on them and saving all nodes with no successor. This however is terribly inefficient, especially since the graph is obviously considerably larger and more complex in my actual project. I was hoping for a simple and efficient method such as G.out_nodes() or something similar that is keeping track of the output nodes when the graph is edited, though I seem to be unable to find it. However since determining output and input nodes in a directed graph is no uncommon task am I of the opinion that I am missing something. I was hoping that you might be able to help me. Thank you very much.

Once you have your graph you could iterate and get the nodes with out_degree equal to 0.

output_nodes = [u for u, deg in g.out_degree() if not deg]

However, you could get them directly when building your graph, indeed you could remove from the nodes u if (u,v) is an arc. The remaining will be output nodes.
Another possibility is to use another way to represent your graph according to size/most common operations to be applied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM