[WIP] Solution for problem 9
This commit is contained in:
parent
f100875d3d
commit
3f06cdb0bd
|
@ -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)}")
|
Loading…
Reference in New Issue