diff --git a/src/Year_2015/P9.py b/src/Year_2015/P9.py new file mode 100644 index 0000000..6a5959e --- /dev/null +++ b/src/Year_2015/P9.py @@ -0,0 +1,32 @@ +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")] + +# print(routes) +G = nx.Graph() +for route in routes: + cities, dist = route.split(" = ") + from_, to_ = cities.split(" to ") + # print(from_, to_, dist) + G.add_edge(from_, to_, weight=int(dist)) + +# print(G.nodes()) + + +cycle = nx_app.christofides(G, weight="weight") +print(cycle) +edge_list = list(nx.utils.pairwise(cycle)) +print(edge_list) + +paths = [] +for f in cycle: + for t in cycle: + 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")) + +print(f"Solution {min(paths)}") +print(f"Solution {max(paths)}")