Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is based on Alex Martelli's answer, but it should work. It depends on the expression <code>source_node.children</code> yielding an iterable that will iterate over all the children of <code>source_node</code>. It also relies on there being a working way for the <code>==</code> operator to compare two nodes to see if they are the same. Using <code>is</code> may be a better choice. Apparently, in the library you're using, the syntax for getting an iterable over all the children is <code>graph[source_node]</code>, so you will need to adjust the code accordingly.</p> <pre><code>def allpaths(source_node, sink_node): if source_node == sink_node: # Handle trivial case return frozenset([(source_node,)]) else: result = set() for new_source in source_node.children: paths = allpaths(new_source, sink_node, memo_dict) for path in paths: path = (source_node,) + path result.add(path) result = frozenset(result) return result </code></pre> <p>My main concern is that this does a depth first search, it will waste effort when there are several paths from the source to a node that's a grandchild, great grandchild, etc all of source, but not necessarily a parent of sink. If it memoized the answer for a given source and sink node it would be possible to avoid the extra effort.</p> <p>Here is an example of how that would work:</p> <pre><code>def allpaths(source_node, sink_node, memo_dict = None): if memo_dict is None: # putting {}, or any other mutable object # as the default argument is wrong memo_dict = dict() if source_node == sink_node: # Don't memoize trivial case return frozenset([(source_node,)]) else: pair = (source_node, sink_node) if pair in memo_dict: # Is answer memoized already? return memo_dict[pair] else: result = set() for new_source in source_node.children: paths = allpaths(new_source, sink_node, memo_dict) for path in paths: path = (source_node,) + path result.add(path) result = frozenset(result) # Memoize answer memo_dict[(source_node, sink_node)] = result return result </code></pre> <p>This also allows you to save the memoization dictionary between invocations so if you need to compute the answer for multiple source and sink nodes you can avoid a lot of extra effort.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload