Python Progression Path - from Apprentice to Guru

Python progression path - From apprentice to guru

I thought the process of Python mastery went something like:

  1. Discover list comprehensions
  2. Discover generators
  3. Incorporate map, reduce, filter, iter, range, xrange often into your code
  4. Discover Decorators
  5. Write recursive functions, a lot
  6. Discover itertools and functools
  7. Read Real World Haskell (read free online)
  8. Rewrite all your old Python code with tons of higher order functions, recursion, and whatnot.
  9. Annoy your cubicle mates every time they present you with a Python class. Claim it could be "better" implemented as a dictionary plus some functions. Embrace functional programming.
  10. Rediscover the Strategy pattern and then all those things from imperative code you tried so hard to forget after Haskell.
  11. Find a balance.

Find Networkx path by a sequence of nodes

There's some reading between the lines that you've left for us. For example, are you specifically looking for paths that end in node 7 in this case, or are you just looking for any path that has nowhere else to go (i.e. ends in a node of outdegree zero)? If the path contains a cycle, do we include paths that go around the cycle before ending?

My guess is that what you're really interested in is the set of all simple paths from a given node that end in a node with outdegree zero. With that in mind, here's some code you might find useful.

start = 1
ends = [n for n in DG.nodes if DG.out_degree[n] == 0]
paths = [p for e in ends
for p in nx.all_simple_paths(DG, source = start, target = e)]
print(paths)

Output: [[1, 2, 4, 5, 6, 7], [1, 2, 3, 6, 7]]


If you want paths that start from 1 and end in any other node, you could do the following.

start = 1
paths = [p for e in DG.nodes
for p in nx.all_simple_paths(DG, source = start, target = e)]
print(paths)

Output: [[1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 4, 5, 6], [1, 2, 3, 6], [1, 2, 4, 5, 6, 7], [1, 2, 3, 6, 7], [1, 2, 4, 5]].

If you like, you can take this output and filter down to the paths that start with any 3 nodes. For example,

print([p for p in paths if p[:3] == [1,2,3]])
print([p for p in paths if p[:3] == [1,2,4]])

results in the outputs [[1, 2, 3], [1, 2, 3, 6], [1, 2, 3, 6, 7]] and [[1, 2, 4], [1, 2, 4, 5, 6], [1, 2, 4, 5, 6, 7], [1, 2, 4, 5]].

Alternatively, sorting paths naturally organizes the paths according to their first nodes. In particular, sorted(paths) is the list

[[1, 2],
[1, 2, 3],
[1, 2, 3, 6],
[1, 2, 3, 6, 7],
[1, 2, 4],
[1, 2, 4, 5],
[1, 2, 4, 5, 6],
[1, 2, 4, 5, 6, 7]]

which you could split into two pieces.



Related Topics



Leave a reply



Submit