shortest_path
Builtin index · Collections & strings
result = shortest_path(g, from, to)
Input: g, from, to · Output: result
What it is
g is a graph handle; from/to are node ids.
Overloads
One call shape — this function is not overloaded.
| Code | Input | Output | Description |
result = shortest_path(g, from, to) | g —g is a graph handle.from —from/to are node ids.to —from/to are node ids. | number —the shortest total edge weight, via Dijkstra | Returns a number (the shortest total edge weight, via Dijkstra) or none if to is unreachable from from — disconnected is an answer, not an error. Errors instead if from/to isn't even a node in g. Same free-function form as .shortest_path, not the sequence of node names along the route. |
Examples
From the documentation, and run by the build -- the output and the figure below are what the engine actually produced. Simplest first.
g = graph()
g.add_edge("A", "B", weight=4)
g.add_edge("A", "C", weight=1)
g.add_edge("C", "B", weight=2)
g.add_edge("B", "D", weight=5)
g.add_edge("C", "D", weight=8)
print(g.shortest_path("A", "D")) # 8, via A -> C -> B -> D (1 + 2 + 5)
output
8
from collections-strings
How it works
graph([directed=]) (§ data structures pass, 2026-09-01, algorithm, Dijkstra's shortest_path; see that module's own doc comment for the node-id normalization rule and why Dijkstra over plain BFS.
From the note above this builtin in the interpreter, where the reasoning was written down as it was built.