Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/algorithm_theory/union_find.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 14 additions & 0 deletions tests/algorithm_theory/test_union_find.py
Original file line number Diff line number Diff line change
@@ -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
Loading