Created
June 17, 2014 07:24
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is from my first paid project. Made $200 and realized I could make money doing this, and now it's 8 years later.