Coursera-Stanford-Graph-Search-Shortest-Paths-and-Data-Structures
Coursera-Stanford-Graph-Search-Shortest-Paths-and-Data-Structures copied to clipboard
Algorithms are Obsolete.
The algorithms that you have used no more give the correct solutions for the Assignments!
Yes they are. I tried doing the questions on my own but was struggling a lot. Decided to look up for solutions to see how they work and found this. I have been trying to make this work but these are obsolete and do not run or even if they do, the solutions are wrong.
heres the code that works if anyone is still looking for the answers
import time
file_path = "clustering1.txt"
with open(file_path, "r") as file: num_nodes = int(file.readline()) clusters = {x: [x] for x in range(1, num_nodes + 1)} edges = [] for line in file: node1, node2, cost = map(int, line.strip().split()) edges.append((node1, node2, cost)) sorted_edges = sorted(edges, key=lambda x: x[2])
k = 4
def get_key_by_value(d, k): for leader, nodes in d.items(): if k in nodes: return leader
def update_clusters(c, a, d): c[a].extend(c[d]) del c[d]
iteration = 0
start_time = time.time()
for edge in sorted_edges: node1, node2, cost = edge key1 = get_key_by_value(clusters, node1) key2 = get_key_by_value(clusters, node2) if key1 == key2: continue elif len(clusters[key1]) >= len(clusters[key2]): update_clusters(clusters, key1, key2) else: update_clusters(clusters, key2, key1) if len(clusters) == k: break
max_spacing = None
for edge in sorted_edges: node1, node2, cost = edge key1 = get_key_by_value(clusters, node1) key2 = get_key_by_value(clusters, node2) if key1 != key2: max_spacing = cost break
end_time = time.time() execution_time = end_time - start_time
print("Execution time: {:.6f} seconds".format(execution_time)) print("Execution time: {:.6f} minutes".format(execution_time / 60)) print("Execution time: {:.6f} hours".format(execution_time / 3600)) print("Maximum spacing of a 4-clustering: ", max_spacing)
i was able to do it