Created
November 27, 2015 20:32
-
-
Save znerol/234c29623b96dad5de61 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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