DSA Mini Project
In this project you'll build a small metro journey planner, one step at a time. It combines many structures and algorithms from the course: a graph stored as adjacency lists, BFS for the fewest stops, Dijkstra with a heap for the fastest route, a trie for station-name autocomplete, a hash map for passenger counts and a heap for the busiest stations.
The metro network:
Airport ─6─ Harbor ─4─ Museum ─3─ Center ─2─ Market
│ │ │ │
5 2 4 3
│ │ │ │
Docks ─7─ Park ─────3──── Campus ─5─ Stadium(Weights are travel times in minutes. Park and Campus are connected directly with 3 minutes.)
Step 1: Load the network
Each connection is written as text, the way it might come from a file. We parse it into an adjacency map {station: {neighbour: minutes}} and check some basic facts.
NETWORK = """
Airport-Harbor 6
Harbor-Museum 4
Museum-Center 3
Center-Market 2
Harbor-Docks 5
Museum-Park 2
Center-Campus 4
Market-Stadium 3
Docks-Park 7
Park-Campus 3
Campus-Stadium 5
"""
def load(text):
graph = {}
for line in text.strip().splitlines():
pair, minutes = line.split()
a, b = pair.split("-")
graph.setdefault(a, {})[b] = int(minutes)
graph.setdefault(b, {})[a] = int(minutes) # tracks run both ways
return graph
metro = load(NETWORK)
edges = sum(len(n) for n in metro.values()) // 2
print(f"{len(metro)} stations, {edges} connections")
for station in sorted(metro):
links = ", ".join(f"{n} {m}" for n, m in sorted(metro[station].items()))
print(f" {station:<8} -> {links}")9 stations, 11 connections
Airport -> Harbor 6
Campus -> Center 4, Park 3, Stadium 5
Center -> Campus 4, Market 2, Museum 3
Docks -> Harbor 5, Park 7
Harbor -> Airport 6, Docks 5, Museum 4
Market -> Center 2, Stadium 3
Museum -> Center 3, Harbor 4, Park 2
Park -> Campus 3, Docks 7, Museum 2
Stadium -> Campus 5, Market 3
Step 2: Fewest stops with BFS
Some passengers hate changing trains more than they hate waiting. BFS finds the route with the fewest stops, ignoring the minutes. Here is the search animated on the network, starting from Airport:
from collections import deque
NETWORK = """Airport-Harbor 6
Harbor-Museum 4
Museum-Center 3
Center-Market 2
Harbor-Docks 5
Museum-Park 2
Center-Campus 4
Market-Stadium 3
Docks-Park 7
Park-Campus 3
Campus-Stadium 5"""
metro = {}
for line in NETWORK.splitlines():
pair, minutes = line.split()
a, b = pair.split("-")
metro.setdefault(a, {})[b] = int(minutes)
metro.setdefault(b, {})[a] = int(minutes)
def fewest_stops(graph, start, goal):
parent = {start: None}
queue = deque([start])
while queue:
u = queue.popleft()
if u == goal:
break
for v in sorted(graph[u]):
if v not in parent:
parent[v] = u
queue.append(v)
route = []
while goal is not None:
route.append(goal)
goal = parent[goal]
return route[::-1]
def minutes(graph, route):
return sum(graph[a][b] for a, b in zip(route, route[1:]))
for goal in ["Stadium", "Campus"]:
route = fewest_stops(metro, "Airport", goal)
print(f"Airport -> {goal}: {' > '.join(route)} ({len(route) - 1} stops, {minutes(metro, route)} min)")Airport -> Stadium: Airport > Harbor > Docks > Park > Campus > Stadium (5 stops, 26 min)
Airport -> Campus: Airport > Harbor > Docks > Park > Campus (4 stops, 21 min)
Step 3: Fastest route with Dijkstra
Most passengers want the fastest route. Dijkstra's algorithm with a heap handles the travel times:
import heapq
NETWORK = """Airport-Harbor 6
Harbor-Museum 4
Museum-Center 3
Center-Market 2
Harbor-Docks 5
Museum-Park 2
Center-Campus 4
Market-Stadium 3
Docks-Park 7
Park-Campus 3
Campus-Stadium 5"""
metro = {}
for line in NETWORK.splitlines():
pair, m = line.split()
a, b = pair.split("-")
metro.setdefault(a, {})[b] = int(m)
metro.setdefault(b, {})[a] = int(m)
def fastest(graph, start, goal):
heap = [(0, start, [start])]
done = set()
while heap:
time, station, route = heapq.heappop(heap)
if station == goal:
return time, route
if station in done:
continue
done.add(station)
for nxt, m in sorted(graph[station].items()):
if nxt not in done:
heapq.heappush(heap, (time + m, nxt, route + [nxt]))
return None
for goal in ["Stadium", "Campus", "Docks"]:
time, route = fastest(metro, "Airport", goal)
print(f"Airport -> {goal}: {' > '.join(route)} ({time} min)")Airport -> Stadium: Airport > Harbor > Museum > Center > Market > Stadium (18 min)
Airport -> Campus: Airport > Harbor > Museum > Park > Campus (15 min)
Airport -> Docks: Airport > Harbor > Docks (11 min)
Step 4: Penalise line changes
Real metros have lines, and changing lines costs time (walking, waiting). We model each station on each line as its own vertex, "Center@red", and add a transfer edge of 4 minutes between the copies of the same station. Dijkstra doesn't need to change at all; only the graph does:
import heapq
LINES = {
"red": [("Airport", 6), ("Harbor", 4), ("Museum", 3), ("Center", 2), ("Market", 0)],
"blue": [("Docks", 7), ("Park", 3), ("Campus", 5), ("Stadium", 0)],
"green": [("Harbor", 5), ("Docks", 0)],
"yellow": [("Museum", 2), ("Park", 0)],
"orange": [("Center", 4), ("Campus", 0)],
"pink": [("Market", 3), ("Stadium", 0)],
}
TRANSFER = 4
graph = {}
def link(a, b, m):
graph.setdefault(a, {})[b] = m
graph.setdefault(b, {})[a] = m
where = {}
for line, stops in LINES.items():
for (s, m), (t, _) in zip(stops, stops[1:]):
link(f"{s}@{line}", f"{t}@{line}", m)
for s, _ in stops:
where.setdefault(s, []).append(f"{s}@{line}")
for copies in where.values():
for i, a in enumerate(copies):
for b in copies[i + 1:]:
link(a, b, TRANSFER)
def fastest(start, goal):
heap = [(0, v, [v]) for v in where[start]]
heapq.heapify(heap)
done = set()
while heap:
time, node, route = heapq.heappop(heap)
if node.split("@")[0] == goal:
return time, route
if node in done:
continue
done.add(node)
for nxt, m in graph[node].items():
if nxt not in done:
heapq.heappush(heap, (time + m, nxt, route + [nxt]))
def describe(route):
legs, line = [], None
for node in route:
station, l = node.split("@")
if l != line:
legs.append(f"[{l}] {station}")
line = l
else:
legs[-1] += f" > {station}"
return " | ".join(legs)
time, route = fastest("Airport", "Stadium")
print(f"{time} min: {describe(route)}")
time, route = fastest("Docks", "Market")
print(f"{time} min: {describe(route)}")22 min: [red] Airport > Harbor > Museum > Center > Market | [pink] Market > Stadium
18 min: [green] Docks > Harbor | [red] Harbor > Museum > Center > Market
Each | is a change of line, and each change adds 4 minutes, so routes with fewer changes become more attractive.
Step 5: Autocomplete station names with a trie
The search box suggests stations as the passenger types. A trie returns all names with the typed prefix, in alphabetical order:
class TrieNode:
def __init__(self):
self.children, self.word = {}, None
class Trie:
def __init__(self, words):
self.root = TrieNode()
for w in words:
node = self.root
for ch in w.lower():
node = node.children.setdefault(ch, TrieNode())
node.word = w # keep the original spelling
def suggest(self, prefix):
node = self.root
for ch in prefix.lower():
node = node.children.get(ch)
if node is None:
return []
out, stack = [], [node]
while stack: # DFS, children pushed in reverse order
n = stack.pop()
if n.word:
out.append(n.word)
stack.extend(n.children[c] for c in sorted(n.children, reverse=True))
return out
stations = ["Airport", "Harbor", "Museum", "Center", "Market", "Docks", "Park",
"Campus", "Stadium", "Central Library", "Cathedral"]
names = Trie(stations)
for typed in ["c", "ce", "ma", "st", "x"]:
print(f"{typed!r:>5}: {names.suggest(typed)}") 'c': ['Campus', 'Cathedral', 'Center', 'Central Library']
'ce': ['Center', 'Central Library']
'ma': ['Market']
'st': ['Stadium']
'x': []
Step 6: The busiest stations
Finally, the operator wants a daily report. Each ticket is a start-end trip. A hash map counts how often each station appears, and a heap picks the top three without sorting everything:
import heapq
from collections import Counter
trips = """Airport-Center Harbor-Park Center-Stadium Park-Campus Airport-Market
Campus-Center Market-Center Docks-Park Center-Airport Stadium-Campus
Museum-Park Park-Center Harbor-Airport Center-Campus Market-Stadium""".split()
visits = Counter()
for trip in trips:
start, end = trip.split("-")
visits[start] += 1
visits[end] += 1
top = heapq.nlargest(3, visits.items(), key=lambda kv: (kv[1], kv[0]))
print(f"{len(trips)} trips, {sum(visits.values())} station visits")
for station, count in top:
print(f" {station:<8} {count:>2} {'#' * count}")
quiet = sorted(s for s in visits if visits[s] == min(visits.values()))
print("quietest:", quiet)15 trips, 30 station visits
Center 7 #######
Park 5 #####
Campus 4 ####
quietest: ['Docks', 'Museum']
Ideas for extending the project
- Minimum spanning tree: which tracks would a cheaper network keep so that every station stays connected? (Run Kruskal's algorithm on
NETWORK.) - Closures: remove a connection and rerun Dijkstra; use BFS to check whether the network is still connected.
- Departure times: add timetables and search over
(station, time)states. - A*: give each station coordinates and use the straight-line distance as a heuristic to speed up the search.
Test yourself
Which algorithm in the project finds the route with the fewest stops?
- Dijkstra
- BFS
- DFS
- Kruskal
How did step 4 add the cost of changing lines without changing Dijkstra's algorithm?
- By sorting the stations
- By splitting each station into one vertex per line and adding transfer edges
- By using a stack
- By removing lines
Why use a trie for station autocomplete instead of a hash set?
- Tries use less memory
- Tries find all names that start with a prefix in one walk
- Hash sets can't store strings
- Tries keep counts