I'm using networkx and trying to find all the walks with length 3 in the graph, specifically the paths with three edges. I tried to find some information about the algorithms in the networkx documentation but I could only find the algorithms for the shortest path in the graph. Can I find a length of a path trough specific nodes, for example a path trough nodes 14 -> 11 -> 12 -> 16 if the shortest path is 14 -> 15 -> 16? Here's an image of a graph for an example http://i62.tinypic.com/2ekj602.jpg
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Simplest version (another version is below which I think is faster):
This takes a network
G
and a nodeu
and a lengthn
. It recursively finds all paths of length n-1 starting from neighbors ofu
that don't includeu
. Then it sticksu
at the front of each such path and returns a list of those paths.Note, each path is an ordered list. They all start from the specified node. So for what you want, just wrap a loop around this:
Note that this will have any
a-b-c-d
path as well as the reversed-c-b-a
path.If you find the "list comprehension" to be a challenge to interpret, here's an equivalent option:
For optimizing this, especially if there are many cycles, it may be worth sending in a set of disallowed nodes. At each nested call it would know not to include any nodes from higher up in the recursion. This would work instead of the
if u not in path
check. The code would be a bit more difficult to understand, but it would run faster.Note that I have to add
u
toexcludeSet
before the recursive call and then remove it before returning.