-
-
Save disouzam/0a574fd4dd74de6d28458a5bb12bd9c0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| from collections import defaultdict | |
| from graphlib import TopologicalSorter | |
| from heapq import heappush, heappop, heapify | |
| def topo_lex(pairs): | |
| deps = defaultdict(set) # node -> set(dependencies) | |
| for a, b in pairs: | |
| deps.setdefault(a, set()) | |
| deps[b].add(a) | |
| ts = TopologicalSorter(deps) | |
| ts.prepare() | |
| pq = list(ts.get_ready()) | |
| heapify(pq) | |
| out = [] | |
| while pq: | |
| n = heappop(pq) # smallest ready node | |
| out.append(n) | |
| ts.done(n) | |
| for r in ts.get_ready(): | |
| heappush(pq, r) | |
| if len(out) != len(deps): | |
| raise ValueError("cycle") | |
| return "".join(out) | |
| pairs = [ | |
| ("C", "A"), | |
| ("C", "F"), | |
| ("A", "B"), | |
| ("A", "D"), | |
| ("B", "E"), | |
| ("D", "E"), | |
| ("F", "E"), | |
| ] | |
| assert topo_lex(pairs) == "CABDFE" |
Author
Author
As pointed out by @bbelderbos in the original gist, the correct challenge in which this algorithm was used is 2018 Advent of Code's Day 7 challenge: https://adventofcode.com/2018/day/7
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Useful references: