Skip to content

Instantly share code, notes, and snippets.

@hxegon
Created June 17, 2014 07:24
Show Gist options
  • Save hxegon/775b3d75fad37c52ba02 to your computer and use it in GitHub Desktop.
Save hxegon/775b3d75fad37c52ba02 to your computer and use it in GitHub Desktop.
Working on path finding for directional acyclic graphs. Need some help with list comprehension.
import networkx as nx
G = nx.DiGraph()
G.add_nodes_from([ i for i in range(0, 5) ])
G.add_edges_from([(0,1), (0,2), (1, 3), (1, 4)])
class Finder:
def __init__(self, graph):
self.graph = graph
def find_paths_from(self, start_point):
neighbors = self.graph.neighbors(start_point) # Find all other nodes start_point can connect to
if neighbors == []:
return [start_point]
else:
return [ [start_point] + self.find_paths_from(n) for n in neighbors ]
F = Finder(G)
F.find_paths_from(0) #=> [[0, [1, 3], [1, 4]], [0,2]]
# I want this to return [[0, 1, 3], [0, 1, 4], [0, 2]], How can I do that?
@hxegon
Copy link
Author

hxegon commented Aug 28, 2022

This is from my first paid project. Made $200 and realized I could make money doing this, and now it's 8 years later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment