Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 78 / 101

When every edge has a cost.

Use a priority queue for nonnegative weighted paths and ignore stale entries.

ADVANCED LAB
BY NAVAN SAMI◷ 12 MIN READPYTHON 3

01 The idea

Dijkstra’s algorithm repeatedly settles the smallest tentative distance. It works when edge costs are nonnegative. A min-heap prioritises the next candidate, and a distance map stores the best cost found so far. This implementation pushes improved distances rather than modifying heap entries in place; outdated entries are skipped when popped.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

dijkstra.py
import heapq

def distances(graph, start):
    best, queue = {start: 0}, [(0, start)]
    while queue:
        cost, node = heapq.heappop(queue)
        if cost != best[node]: continue
        for neighbour, weight in graph.get(node, []):
            if weight < 0: raise ValueError("Nonnegative weights required")
            candidate = cost + weight
            if candidate < best.get(neighbour, float("inf")):
                best[neighbour] = candidate
                heapq.heappush(queue, (candidate, neighbour))
    return best
graph = {"A": [("B", 4), ("C", 1)], "C": [("B", 2)], "B": []}
print(distances(graph, "A")["B"])
↳ EXPECTED OUTPUT
3

03 Under the hood

  1. 1

    A→C→B costs three, improving on the direct edge cost four. The priority queue explores candidates by total cost, not edge count.

  2. 2

    An older candidate for B can remain in the heap after a better route is found. The stale-entry check prevents redundant processing.

  3. 3

    This fixture uses comparable string vertex names, so equal heap costs can compare the second tuple element. Arbitrary vertex objects need a counter tie-breaker. Validate all reachable edge weights and choose a different algorithm if negatives are allowed.

04 Your turn, builder

A SMALL MISSION

Compare the cost of a direct route with an indirect cheaper route in a small nonnegative graph.

Reveal one possible solution +
one_possible_solution.py
import heapq

def distances(graph, start):
    best, queue = {start: 0}, [(0, start)]
    while queue:
        cost, node = heapq.heappop(queue)
        if cost != best[node]: continue
        for neighbour, weight in graph.get(node, []):
            if weight < 0: raise ValueError("Nonnegative weights required")
            candidate = cost + weight
            if candidate < best.get(neighbour, float("inf")):
                best[neighbour] = candidate
                heapq.heappush(queue, (candidate, neighbour))
    return best
graph = {"A": [("B", 4), ("C", 1)], "C": [("B", 2)], "B": []}
result = distances(graph, "A")
assert result["B"] == 3
print("Direct: 4; best route:", result["B"])

05 Check your signal

QUICK SIGNAL CHECK

What edge-cost restriction does Dijkstra need?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.