#59 · Sort and search

Find the bug · #59 · Sort and search Hard Python

Friend suggestions show people twice

The “people you may know” list shows some people twice.

On this page

The report

Bug report

“People you may know” lists everyone within two steps of you, nearest first. Some people appear twice in the list, usually the ones connected to you through several friends.

The code

Read it first: what should it do? Then click the line where you think the bug is.

PythonClick the line you think is wrong
from collections import deque

def friends_within(graph, start, hops):
    """Everyone within `hops` steps of start (not start), each once, nearest first."""
    seen = {start}
    queue = deque([(start, 0)])
    found = []
    while queue:
        person, dist = queue.popleft()
        if dist == hops:
            continue
        for friend in graph[person]:
            if friend not in seen:
                queue.append((friend, dist + 1))
                found.append(friend)
        seen.add(person)
    return found

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
graph = {
    "Asha": ["Ravi", "Meera"],
    "Ravi": ["Asha", "Kabir"],
    "Meera": ["Asha", "Kabir"],
    "Kabir": ["Ravi", "Meera"],
}
print(friends_within(graph, "Asha", 2))

It prints

['Ravi', 'Meera', 'Kabir', 'Kabir']

It should print

['Ravi', 'Meera', 'Kabir']
Show the answer: the bug, the fix, and how you’d find it

The bug (lines 13, 16)

A person is marked as seen only on line 16, after their whole friend list has been processed, not when they’re first discovered. So Kabir, reached through Ravi, isn’t in seen yet when Meera’s friends are checked, and he’s queued and listed a second time. In a breadth-first search, mark a node as seen when you add it to the queue.

The fix

11            continue12        for friend in graph[person]:13            if friend not in seen:14                seen.add(friend)14                queue.append((friend, dist + 1))15                found.append(friend)16        seen.add(person)17    return found

How you’d find it

  1. Reproduce with a small square of friends: Kabir appears twice, once via Ravi and once via Meera.
  2. Print seen each time a person is taken off the queue: Kabir isn’t in it until he is processed himself, long after he was found.
  3. The check on line 13 looks at seen, so seen must be updated when someone is first found, not after.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

graph = {"a": ["b", "c"], "b": ["a", "d"], "c": ["a", "d"], "d": ["b", "c"]}
result = friends_within(graph, "a", 2)
assert result == ["b", "c", "d"]
assert len(result) == len(set(result))

Where else this bites

  • Grid BFS in DSA problems: mark the cell visited when you push it, or the queue blows up.
  • Web crawlers fetching the same page many times.
Your progress stays on this device.