From cdbc6e539d05159907464b1233d9a8b2fbe7b797 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sat, 8 Aug 2026 10:52:57 -0700 Subject: [PATCH] Add union-find example --- src/algorithm_theory/union_find.py | 38 +++++++++++++++++++++++ tests/algorithm_theory/test_union_find.py | 14 +++++++++ 2 files changed, 52 insertions(+) create mode 100644 src/algorithm_theory/union_find.py create mode 100644 tests/algorithm_theory/test_union_find.py diff --git a/src/algorithm_theory/union_find.py b/src/algorithm_theory/union_find.py new file mode 100644 index 0000000..9612d7b --- /dev/null +++ b/src/algorithm_theory/union_find.py @@ -0,0 +1,38 @@ +class UnionFind: + def __init__(self): + self.roots = [] + + def add_edges(self, n: int, edges: list[tuple[int, int]]): + self.roots = [number for number in range(n)] + for edge in edges: + a, b = edge + self.union(a, b) + + def components(self) -> int: + count = 0 + + for index in range(len(self.roots)): + if self.roots[index] == index: + count += 1 + + return count + + def union(self, a: int, b: int): + root_a = self.find(a) + root_b = self.find(b) + + if root_a is not None and root_b is not None: + self.roots[root_a] = root_b + + def find(self, node1: int) -> None | int: + stack = [node1] + + while stack: + current = stack.pop() + if self.roots[current] == current: + return current + stack.append(self.roots[current]) + return None + + def size(self) -> int: + return len(self.roots) diff --git a/tests/algorithm_theory/test_union_find.py b/tests/algorithm_theory/test_union_find.py new file mode 100644 index 0000000..feb22ff --- /dev/null +++ b/tests/algorithm_theory/test_union_find.py @@ -0,0 +1,14 @@ +from src.algorithm_theory.union_find import UnionFind + + +def test_initializer(): + union_find = UnionFind() + assert union_find.size() == 0 + assert union_find.components() == 0 + + +def test_components(): + union_find = UnionFind() + union_find.add_edges(7, [(0, 2), (1, 0), (4, 3), (2, 5), (3, 6)]) + + assert union_find.components() == 2