From d6722c798f3a07d9df0eed6281c576242b7e14ec Mon Sep 17 00:00:00 2001 From: daviddoji Date: Mon, 27 Jul 2026 21:16:43 +0200 Subject: [PATCH] Optimized solution --- src/Year_2015/P9.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/Year_2015/P9.py b/src/Year_2015/P9.py index df5d996..9a12e09 100644 --- a/src/Year_2015/P9.py +++ b/src/Year_2015/P9.py @@ -32,8 +32,6 @@ from itertools import permutations import networkx as nx -import networkx.algorithms.approximation as nx_app -from networkx.classes.function import path_weight with open("files/P9.txt") as f: routes = [line for line in f.read().strip().split("\n")] @@ -44,13 +42,10 @@ for route in routes: from_, to_ = cities.split(" to ") G.add_edge(from_, to_, weight=int(dist)) -cycle = nx_app.christofides(G, weight="weight") - paths = [] -for f, t in permutations(cycle, 2): - for path in nx.all_simple_paths(G, source=f, target=t): - if len(path) == len(cycle) - 1: - paths.append(path_weight(G, path, weight="weight")) +for route in permutations(G.nodes): + distance = sum(G[u][v]["weight"] for u, v in zip(route, route[1:])) + paths.append(distance) def part_1() -> None: