Created
October 17, 2025 16:49
-
-
Save bbelderbos/f577bf2c35ffd575696df089842c4731 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, thanks. This was for 2018 - day 07 actually.