Capstone — Recommendations
In short: Ana's Discover page should fill with tracks her network plays —
and a close friend's favourite should outrank a stranger three follows away.
That's this whole section in one feature: a graph of follows, a BFS
traversal capped at max_hops that finds who's nearby and how near, and a
weighted tally that turns nearness into influence. Every piece — capped
BFS O(V + E) within the radius, a tally over the plays found, and a final
O(K log K) sort of K candidate tracks — is something you've already built in
this section. This capstone wires them together.

recommend_for(follows, plays, listener, max_hops)follows— the follow graph, an adjacency dict. A name with no key follows nobody.plays— each listener's tracks, e.g.{"ben": ["Drift", "Glow"]}. No repeats within one list; a listener with no key plays nothing.listener— who the recommendations are for.max_hops— how far out to look.
The rules, in order: walk the follows breadth-first from listener out to
max_hops hops; every listener found at distance d (1 ≤ d ≤ max_hops)
has a weight of max_hops - d + 1; each adds their weight to every track
they play, except tracks listener already plays; return [track, score]
pairs, highest score first, ties alphabetically. Worked by hand with
max_hops = 2:
| Listener | Hops from ana | Weight | Plays | Adds |
|---|---|---|---|---|
| ben | 1 | 2 | Drift, Glow | Drift +2 (Glow skipped — ana plays it) |
| cal | 1 | 2 | Drift | Drift +2 |
| dia | 2 | 1 | Aura | Aura +1 |
So recommend_for(follows, plays, "ana", 2) → [["Drift", 4], ["Aura", 1]].
Finding Ana's neighbourhood
This is BFS from the BFS lesson, with one addition: don't expand anyone
already max_hops out. The hops dict records distance and doubles as the
visited set, so follow loops can't send you round forever. With
max_hops = 2, Eli — whom Dia follows, three hops out — gets no vote at all:
A capped BFS finds who is near and how near, and nobody past max_hops gets a vote.
The walk starts at Ana, 0 hops out, and she never votes on her own page. 5 nodes, 6 edges, directed. At ana. Settled: ana. ana: 0.
The mistake: forgetting that listener is still in hops at distance 0
— skip distance 0 when you tally, or Ana ends up voting for her own tracks:
from collections import deque
follows = {"ana": ["ben", "cal"], "ben": ["dia"], "cal": ["dia"], "dia": ["ana"]}
hops = {"dia": 0}
queue = deque(["dia"])
while queue:
name = queue.popleft()
if hops[name] >= 2:
continue
for nxt in follows.get(name, []):
if nxt not in hops:
hops[nxt] = hops[name] + 1
queue.append(nxt)
print(sorted(hops))