interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / dijkstras-algorithm / oracle.py

24 lines · 1028 bytes Raw Blame History
1# Independent reference for "Dijkstra's algorithm" (Python 3, standard library only).
2# expected.txt is this program's stdout; omc never produced it.
3def simple_paths(adj, s, t, seen=()):
4 if s == t:
5 yield (s,)
6 return
7 for v in adj.get(s, {}):
8 if v not in seen and v != s:
9 for p in simple_paths(adj, v, t, seen + (s,)):
10 yield (s,) + p
11def best(adj, s, t):
12 cands = sorted((sum(adj[p[i]][p[i + 1]] for i in range(len(p) - 1)), p) for p in simple_paths(adj, s, t))
13 if not cands:
14 return None
15 assert len(cands) == 1 or cands[0][0] < cands[1][0], "shortest path not unique"
16 return cands[0]
17# checked by enumerating every simple path, not by a priority queue
18adj = {"a": {"b": 7, "c": 9, "f": 14}, "b": {"c": 10, "d": 15}, "c": {"d": 11, "f": 2}, "d": {"e": 6}, "e": {"f": 9}}
19for t in "bcdef":
20 r = best(adj, "a", t)
21 if r is None:
22 print(f"a -> {t} unreachable")
23 else:
24 print(f"a -> {t} cost {r[0]} path " + " ".join(r[1]))