I am wondering if anyone has any ideas for improving the following. Personally I am 'happy' with it, apart from the first for
loop. I was thinking of another way of writing this, but perhaps it is ok.
def findnodepaths(nodepaths, graph, *nodes):
# nodepaths == list()
# graph == defaultdict(set)
# *nodes == 'foo','bar',... possible items in the graph
nodeset = set(nodes) & set(graph.keys())
# nodeset == nodes that are in the graph ... avoids try / if
nodepaths = [(nodeA,weight,nodeB) for nodeA in nodeset for (nodeB,weight) in graph[nodeA]]
for path in nodepaths:
# for every item in list
*xs, nodeA = path
# nodeA == last value added, xs == all the rest
for (nodeB,weight) in graph[nodeA]:
# search again ... just like we all ready have
if nodeB not in xs:
# if new val not in the triple / quadruple ...
nodepaths.append( path + (weight,nodeB) )
# add new item to list based on its match
# repeat until no new paths can be found
return nodeset, nodepaths
# return nodes that were found + all of their paths