def get_clusters_two_spaces(graph_nodes): union_find = UnionFind() for vertex in list(graph_nodes): union_find.add_vertex(vertex) clusters = len(graph_nodes) for u in list(graph_nodes): u_neighbours = set(generate_neighbours(u)) u_second_neighbours = set() u_second_neighbours = u_second_neighbours.union(u_neighbours) for neighbour in u_neighbours: next_neighbours = generate_neighbours(neighbour) u_second_neighbours = u_second_neighbours.union(next_neighbours) #u_second_neighbours = generate_second_neighbours(u) actual_neighbours = set(u_second_neighbours).intersection(graph_nodes) for v in actual_neighbours: if u == v: continue root_u = union_find.path_compress_find(u) root_v = union_find.path_compress_find(v) if root_u == root_v: continue else: clusters -= 1 union_find.union(root_u, root_v) return union_find, clusters
def max_space_clustering(edges, vertices, clusters): union_find = UnionFind() for vertex in vertices: union_find.add_vertex(vertex) edges = sorted(edges, key=(lambda x: x.dist)) e = 0 for edge in edges: rootu = union_find.path_compress_find(edge.u) rootv = union_find.path_compress_find(edge.v) if e == len(vertices) - clusters: if rootu != rootv: max_spacing = edge.dist break else: continue if rootu == rootv: continue else: union_find.union(edge.u, edge.v) e += 1 root_parents = dict() for vertex in list(vertices): root_parents[vertex] = union_find.path_compress_find(vertex) return root_parents, max_spacing