Skip to content

Instantly share code, notes, and snippets.

@bencharb
Created February 24, 2016 06:05
Show Gist options
  • Save bencharb/5c93e117321c0b59ef13 to your computer and use it in GitHub Desktop.
Save bencharb/5c93e117321c0b59ef13 to your computer and use it in GitHub Desktop.
get basic graph dependencies
def get_dependencies(node, edges_list, depth=0):
if depth > len(edges_list):
raise Exception('Circular dependency somewhere.')
seen_nodes = set()
for from_node, to_node in edges_list:
if from_node == node:
seen_nodes.add(from_node)
if to_node in seen_nodes:
continue
yield to_node
nested_deps = []
for to_dep in get_dependencies(to_node, edges_list, depth=depth+1):
nested_deps.append(to_dep)
if nested_deps:
for nd in nested_deps:
yield nd
def test_get_dependencies():
result = list(get_node_dependencies('a', (['a','b'],['b','d'], ['c','d'],['d','e'],)))
expected = ['b', 'd', 'e']
assert result == expected
test_get_dependencies()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment