Skip to content

Instantly share code, notes, and snippets.

@znerol
Created November 27, 2015 20:32
Show Gist options
  • Save znerol/234c29623b96dad5de61 to your computer and use it in GitHub Desktop.
Save znerol/234c29623b96dad5de61 to your computer and use it in GitHub Desktop.
def contract(g, f):
"""
Returns a directed acyclic graph with all vertices from the input DAG for
which f() returns True.
"""
vertices = [v for v in g.keys() if f(v)]
result = defaultdict(set, ((v, set()) for v in vertices))
stack = zip(vertices, vertices)
while len(stack):
v, base = stack.pop()
for w in g.get(v, set()):
if f(w):
result[base].add(w)
else:
stack.insert(0, (w, base))
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment