python - Finding all paths/walks of given length in a networkx graph -


I am using the network and am trying to find all aspects of the graph with length 3, especially three Path with edges I tried to find some information about the algorithm in the Network X documentation, but I found only the algorithms for the graph's short term path. Can I get the length of the path trough specific nodes, for example path path nodes 14 -> 11 -> 12 -> 16 if the least route is 14 -> 15 -> 16? Here is an image of a graph for example

Simple version (another version is below which I Seems to be fast):

  def findPaths (g, u, n): if n == 0: returns [[u]] path = [[u] + in the neighboring country Path for ) Path to path (For G, Neighbors, N-1)) If not in Path] Return path  

This is a network G and a node U and a length n . It constantly searches all the paths of time- n starts with the neighbor of u which is not included in u . Then it sticks u to each code and gives a list of those paths.

Note that each path is an order list, starting with all the specified nodes. So, just wrap one loop around the one you want:

node in g: allpaths.extend (findPaths (G, node, 3))

Note that it will have any abcd path, along with the reverse dcba path.

If you have a challenge to interpret "list understanding", here's the same option:

  def findPathsNoLC (G, U, N): If n = = 0: Return [[U]] path = [] Neighbors in G-Nebras (U): Path NOLC (G, Neighborhood, N-1) for Path to Path: If you are not on the path: paths .append ([u] + path) Return path  

To optimize it, especially if there are multiple cycles, it may be able to send in a set of rejected nodes. In each nested call it will be known that the recursive does not include higher nodes. It would be a bit more difficult to understand code if checked if it is not in the path if it is not in the path instead of , but it will run faster. Def findPaths2 (G, U, N, Exclude Set = None): If excludeSet == None: excludeSet = set ([U]) Other: excludeSet.add (u) if N == 0: Return [[U]] path = [[U] + G in the path to neighbors If the lemon (U) is not out in the neighborhood

note that I have to add u to . Set up before recursive call, set and then delete it before returning.


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -