From f45e6f98a5e3f63ac1718a7739235fb10435979f Mon Sep 17 00:00:00 2001 From: Brendan Chen Date: Thu, 20 Aug 2026 18:54:25 -0400 Subject: [PATCH] Add exercise 2 solution --- .../2026.08.11/exercise2_solution.py | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 notes-and-examples/2026.08.11/exercise2_solution.py diff --git a/notes-and-examples/2026.08.11/exercise2_solution.py b/notes-and-examples/2026.08.11/exercise2_solution.py new file mode 100644 index 0000000..94423eb --- /dev/null +++ b/notes-and-examples/2026.08.11/exercise2_solution.py @@ -0,0 +1,55 @@ +# note: I added Anaheim to the sample graph here. The solution should work +# appropriately with either graph. + +sample_graph = { + 'Santa Ana': { + 'Los Angeles': 5, + 'Anaheim': 3, + 'Palm Springs': 50 + }, + 'Anaheim': { + 'Los Angeles': 2, + 'Santa Ana': 3 + }, + 'Los Angeles': { + 'Anaheim': 2, + 'San Francisco': 25, + 'Santa Ana': 5 + }, + 'Palm Springs': { + 'San Francisco': 30, + 'Santa Ana': 50 + }, + 'San Francisco': { + 'Los Angeles': 25, + 'Palm Springs': 30 + } +} + + +def possible_paths(graph: dict[str, dict[str, int]], + start: str, + end: str): + # (path, total distance represented by path) + queue = [([start], 0)] + valid_paths = [] + + # appending to queue: + # append the new vertex to the path, add the distance to the total distance + # do not append to queue if in visited + + while queue: + path, distance = queue.pop(0) + if path[-1] == end: + valid_paths.append((path, distance)) + else: + for vertex, weight in graph[path[-1]].items(): + # question: what can we do to improve time efficiency here? + if vertex not in path: + new_path = path.copy() + new_path.append(vertex) + queue.append((new_path, distance + weight)) + + return valid_paths + +print(possible_paths(sample_graph, 'Santa Ana', 'San Francisco'))