def topological_sort(dependency_pairs):
num_heads = defaultdict(int)  <EOL>tails = defaultdict(list)  <EOL>heads = []  <EOL>for h, t in dependency_pairs:<EOL><INDENT>num_heads[t] += <NUM_LIT:1><EOL>if h in tails:<EOL><INDENT>tails[h].append(t)<EOL><DEDENT>else:<EOL><INDENT>tails[h] = [t]<EOL>heads.append(h)<EOL><DEDENT><DEDENT>ordered = [h for h in heads if h not in num_heads]<EOL>for h in ordered:<EOL><INDENT>for t in tails[h]:<EOL><INDENT>num_heads[t] -= <NUM_LIT:1><EOL>if not num_heads[t]:<EOL><INDENT>ordered.append(t)<EOL><DEDENT><DEDENT><DEDENT>cyclic = [n for n, heads in num_heads.items() if heads]<EOL>return Results(ordered, cyclic)<EOL>
Sort values subject to dependency constraints