def test_Find_OnNotConnectedNodes_ReturnsFalse(self): uf = UnionFind(5) uf.union(1, 2) uf.union(2, 3) uf.union(3, 4) self.assertEqual(uf.find(1), uf.find(3)) self.assertEqual(uf.find(2), uf.find(4)) self.assertNotEqual(uf.find(1), uf.find(5)) self.assertNotEqual(uf.find(4), uf.find(5))
def test_GetCount_OnNonEffectUnions_RemainsTheSame(self): uf = UnionFind(10) uf.union(1, 2) self.assertEqual(uf.count, 9) uf.union(1, 2) self.assertEqual(uf.count, 9) uf.union(2, 3) self.assertEqual(uf.count, 8) uf.union(1, 3) self.assertEqual(uf.count, 8)
def find_clusters(self, count): sorted_edges = sorted(self._edges, key=attrgetter("cost")) uf = UnionFind(self._num_vertices) for index, edge in enumerate(sorted_edges): if count != uf.count and not uf.connected(edge.from_vertex, edge.to_vertex): uf.union(edge.from_vertex, edge.to_vertex) if uf.count == count and not uf.connected(edge.from_vertex, edge.to_vertex): return edge.cost
def find_number_of_clusters(self): uf = UnionFind(self._size) distances = [2 ** i for i in range(self._bits)] distances.extend([-num for num in distances]) for pair in itertools.combinations(distances, 2): bit_1, bit_2 = pair distances.append(bit_1 + bit_2) distances = [0] + distances unions_zero, unions_one, unions_two = [], [], [] for distance in distances: for i in self._numbers.keys(): if (i + distance) in self._numbers: for node_from, bits_from in self._numbers[i]: for node_to, bits_to in self._numbers[i + distance]: if self._hamming(bits_from, bits_to) == 0: unions_zero.append((node_from, node_to)) elif self._hamming(bits_from, bits_to) == 1: unions_one.append((node_from, node_to)) elif self._hamming(bits_from, bits_to) == 2: unions_two.append((node_from, node_to)) self._make_unions(uf, unions_zero) self._make_unions(uf, unions_one) self._make_unions(uf, unions_two) return uf.count
def test_NewUnionFind_WithNoUnions_AllNodesPointToThemselves(self): uf = UnionFind(5) for item in range(1, 5 + 1): self.assertEqual(item, uf.find(item))
def test_GetCount_OnNonConnectedNodes_ReturnInitialSizeAsCount(self): uf = UnionFind(10) self.assertEqual(uf.count, 10)
def test_Union_ThreeNodesInTwoPairs_AllHaveTheSameParent(self): uf = UnionFind(3) uf.union(1, 2) uf.union(2, 3) self.assertEqual(uf.find(1), uf.find(3))
def test_Union_TwoNodes_HaveTheSameParent(self): uf = UnionFind(2) uf.union(1, 2) self.assertEqual(uf.find(1), uf.find(2))