Practice: kiosk routes

Search, sort, and BFS a Kenya city graph, then export a report.

Load the city graph, find hop distances with BFS, sort inventory prices, and write a report. Download graph.json and inventory.csv from the banner and Add files, or let the first block create them.

Goal

Print Nairobi→Eldoret hops, a sorted price list, and a downloadable report.txt.

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

from pathlib import Path

Path("graph.json").write_text(
    '{"Nairobi":["Nakuru","Mombasa"],"Mombasa":["Nairobi","Kisumu"],'
    '"Kisumu":["Mombasa","Nakuru"],"Nakuru":["Nairobi","Kisumu","Eldoret"],'
    '"Eldoret":["Nakuru"]}\n',
    encoding="utf-8",
)
Path("inventory.csv").write_text(
    "product,units,price\nA,12,10.5\nB,7,22.0\nC,2,31.0\nD,9,10.5\n",
    encoding="utf-8",
)
print("wrote graph.json and inventory.csv")

Search, sort, report

import csv
import json
from collections import deque
from pathlib import Path

def hops(graph, start, goal):
    seen = {start}
    q = deque([(start, 0)])
    while q:
        node, dist = q.popleft()
        if node == goal:
            return dist
        for nbr in graph[node]:
            if nbr not in seen:
                seen.add(nbr)
                q.append((nbr, dist + 1))
    return -1

def selection_sort(items):
    xs = list(items)
    n = len(xs)
    for i in range(n):
        lo = i
        for j in range(i + 1, n):
            if xs[j] < xs[lo]:
                lo = j
        xs[i], xs[lo] = xs[lo], xs[i]
    return xs

graph = json.loads(Path("graph.json").read_text(encoding="utf-8"))
print("Nairobi to Eldoret hops", hops(graph, "Nairobi", "Eldoret"))
print("Mombasa to Eldoret hops", hops(graph, "Mombasa", "Eldoret"))

prices = []
with Path("inventory.csv").open(encoding="utf-8", newline="") as handle:
    for row in csv.DictReader(handle):
        prices.append(float(row["price"]))
print("prices", prices)
print("sorted", selection_sort(prices))

lines = [
    "Nairobi kiosk routes",
    "hops Nairobi-Eldoret: " + str(hops(graph, "Nairobi", "Eldoret")),
    "sorted prices: " + ", ".join(str(p) for p in selection_sort(prices)),
]
Path("report.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
print(Path("report.txt").read_text(encoding="utf-8"))

Click on report.txt. You should see 2 hops Nairobi→Nakuru→Eldoret and the sorted prices.

You should see

A graph algorithm, a sort you wrote, and a file. That is the CS loop: represent the data, choose an algorithm, check the output.