Practice: kiosk logistics

Hash inventory, heap of restocks, Dijkstra on edges.csv, write a report.

Hash product prices, push low-stock items on a heap, and Dijkstra Nairobi→Kisumu on the road map. Download inventory.csv and edges.csv from the banner and Add files, or let the first block create them.

Goal

Print a price map, the two lowest-unit products, kilometres to Kisumu, and report.txt.

Seed files (skip if you already attached the banner files)

from pathlib import Path

Path("inventory.csv").write_text(
    "product,units,price\nA,12,10.5\nB,7,22.0\nC,2,31.0\nD,9,10.5\nE,4,22.0\n",
    encoding="utf-8",
)
Path("edges.csv").write_text(
    "from,to,km\nNairobi,Nakuru,160\nNakuru,Nairobi,160\n"
    "Nakuru,Kisumu,180\nKisumu,Nakuru,180\n"
    "Nairobi,Mombasa,480\nMombasa,Nairobi,480\n"
    "Mombasa,Kisumu,550\nKisumu,Mombasa,550\n",
    encoding="utf-8",
)
print("wrote inventory.csv and edges.csv")

Maps, heap, shortest path

import csv
import heapq
from collections import defaultdict
from pathlib import Path

price = {}
units = {}
with Path("inventory.csv").open(encoding="utf-8", newline="") as handle:
    for row in csv.DictReader(handle):
        price[row["product"]] = float(row["price"])
        units[row["product"]] = int(row["units"])
print("price map", price)

low = []
for product, u in units.items():
    heapq.heappush(low, (u, product))
print("lowest units", heapq.heappop(low), heapq.heappop(low))

graph = defaultdict(list)
with Path("edges.csv").open(encoding="utf-8", newline="") as handle:
    for row in csv.DictReader(handle):
        graph[row["from"]].append((row["to"], int(row["km"])))

def dijkstra(graph, start):
    dist = {start: 0}
    pq = [(0, start)]
    while pq:
        d, node = heapq.heappop(pq)
        if d != dist.get(node):
            continue
        for nbr, w in graph[node]:
            nd = d + w
            if nd < dist.get(nbr, nd + 1):
                dist[nbr] = nd
                heapq.heappush(pq, (nd, nbr))
    return dist

km = dijkstra(graph, "Nairobi")["Kisumu"]
print("Nairobi to Kisumu km", km)

lines = [
    "Nairobi kiosk logistics",
    "products: " + str(len(price)),
    "Nairobi-Kisumu km: " + str(km),
]
Path("report.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
print(Path("report.txt").read_text(encoding="utf-8"))

Nairobi → Nakuru → Kisumu is 340 km, cheaper than Nairobi → Mombasa → Kisumu (1030). Click on report.txt.

You should see

A dict for lookup, a heap for “smallest units”, Dijkstra for weighted roads. That is choosing structures by cost, then running them.