python - Identify first node after source node having two neighbors in NetworkX DiGraph -


i implementing digraph networkx. source red-node. need identify first node starting @ red 1 has 2 neighbors (in "flow-direction"). if iterate on nodes - seems ramdom. great if help!

enter image description here

you can use successors method. if digraph instance called g, , red node has index 0 can take breadth first search approach this:

import networkx nx  # construct graph example image, edges pointing away source g = nx.digraph() g.add_path([0,1,2,3,4]) g.add_path([1,5]) g.add_path([3,6]) g.add_path([2,7,8])  # find first 2 neighbors neighbors = g.successors(0) n in neighbors:     nneighbors = set(g.successors(n))     if len(nneighbors) == 2:         print "found", n         break     neighbors.extend(nneighbors) 

the neighbors method interchangable successors digraph in networkx. if want count ingoing edges each node, add g.predecessors(n) set of nneighbors when count them, remember not include them in set when extend neighbors. code be:

# find first 2 neighbors neighbors = g.successors(0) n in neighbors:     if len(g.predecessors(n)+g.successors(n)) == 2:         print "found", n         break     nneighbors = set(g.successors(n))     neighbors.extend(nneighbors) 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -