From 16b4e04483b632402d440c7450ee824664bc1567 Mon Sep 17 00:00:00 2001 From: Brendan Chen Date: Thu, 13 Aug 2026 18:11:14 -0700 Subject: [PATCH] Add the solution file for exercise 1 --- .../2026.08.11/exercise1_solution.py | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 notes-and-examples/2026.08.11/exercise1_solution.py diff --git a/notes-and-examples/2026.08.11/exercise1_solution.py b/notes-and-examples/2026.08.11/exercise1_solution.py new file mode 100644 index 0000000..ebe6aa4 --- /dev/null +++ b/notes-and-examples/2026.08.11/exercise1_solution.py @@ -0,0 +1,60 @@ +# see the overview from 2026.07.31 + +sample_graph = { + 'Alice': set(['Bob', 'Carol']), + 'Bob': set(['Alice', 'Dave']), + 'Carol': set(['Alice', 'Eve', 'Mallory']), + 'Dave': set(['Frank', 'Eve', 'Bob']), + 'Eve': set(['Carol', 'Grace', 'Dave']), + 'Frank': set(['Dave', 'Heidi']), + 'Grace': set(['Eve', 'Ivan', 'Mallory']), + 'Heidi': set(['Frank', 'Ivan']), + 'Ivan': set(['Heidi', 'Grace']), + 'Mallory': set(['Carol', 'Grace']) +} + + +# SOLUTION + +def nth_degree_connections( + graph: dict[str, set[str]], + starting_vertex: str, + max_n: int +): + # what traversal algorithm is this? + + # since we "visit" when looping through neighbors, + # mark the starting vertex as visited already + visited = {starting_vertex} + queue = [(starting_vertex, 0)] # (vertex, n) + + to_return: list[list[str]] = [] + + # check for both conditions at once + # queue is not empty, and we have not exceeded the max_n + while queue and queue[0][1] <= max_n: + element = queue.pop(0) + vertex = element[0] + current_n = element[1] + + if current_n == len(to_return): + to_return.append([]) + to_return[current_n].append(element[0]) + + for neighbor in graph[vertex]: + if neighbor not in visited: + queue.append((neighbor, current_n + 1)) + visited.add(neighbor) + + # we can also + + # match the example: don't include the 0th-degree connection + to_return.pop(0) + return to_return + + +print(nth_degree_connections(sample_graph, 'Mallory', 2)) +print(nth_degree_connections(sample_graph, 'Alice', 4)) +print(nth_degree_connections(sample_graph, 'Ivan', 1)) +print(nth_degree_connections(sample_graph, 'Grace', 0)) +print(nth_degree_connections(sample_graph, 'Carol', 100))