NetworkX — Get all Paths from all sources to sinks

Shane Dowling
Nov 4, 2015 · 1 min read

Often when I’m working with graphs and a set of masses in a spectrum I need to be able to iterate over all paths for all sources and sinks in that graph. Especially if I’m looking to compare multiple ideal spectrums against a given spectrum. Here’s some code that will allow me to quickly iterate over all source->sink paths in a given graph G.

#!/usr/bin/env python
Shane Dowling, 04 Nov 2015
Will iterate over all sources, sinks and get all paths
import networkx as nx
G = nx.DiGraph()
# Fill in a few edges
sink_nodes = [node for node, outdegree in G.out_degree(G.nodes()).items() if outdegree == 0]
source_nodes = [node for node, indegree in G.in_degree(G.nodes()).items() if indegree == 0]
for [(source, sink) for sink in sink_nodes for source in source_nodes]:
for path in nx.all_simple_paths(G, source=source, target=sink):

Tech Blog

Random smattering of technical posts

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store