Last active
July 28, 2024 13:10
-
-
Save kachayev/5990802 to your computer and use it in GitHub Desktop.
Dijkstra shortest path algorithm based on python heapq heap implementation
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
from collections import defaultdict | |
from heapq import * | |
def dijkstra(edges, f, t): | |
g = defaultdict(list) | |
for l,r,c in edges: | |
g[l].append((c,r)) | |
q, seen, mins = [(0,f,())], set(), {f: 0} | |
while q: | |
(cost,v1,path) = heappop(q) | |
if v1 not in seen: | |
seen.add(v1) | |
path = (v1, path) | |
if v1 == t: return (cost, path) | |
for c, v2 in g.get(v1, ()): | |
if v2 in seen: continue | |
prev = mins.get(v2, None) | |
next = cost + c | |
if prev is None or next < prev: | |
mins[v2] = next | |
heappush(q, (next, v2, path)) | |
return float("inf"), None | |
if __name__ == "__main__": | |
edges = [ | |
("A", "B", 7), | |
("A", "D", 5), | |
("B", "C", 8), | |
("B", "D", 9), | |
("B", "E", 7), | |
("C", "E", 5), | |
("D", "E", 15), | |
("D", "F", 6), | |
("E", "F", 8), | |
("E", "G", 9), | |
("F", "G", 11) | |
] | |
print "=== Dijkstra ===" | |
print edges | |
print "A -> E:" | |
print dijkstra(edges, "A", "E") | |
print "F -> G:" | |
print dijkstra(edges, "F", "G") |
friends don't let friends import *
😄
Wildcard imports (from module import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn’t known in advance).
When republishing names this way, the guidelines below regarding public and internal interfaces still apply.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More concise with path reconstruction. The node IDs are represented as integers while the edge weights as floats