Skip to content

Commit 1f5134b

Browse files
authored
Create alternate_disjoint_set.py (TheAlgorithms#2302)
* Create alternate_disjoint_set.py This code implements a disjoint set using Lists with added heuristics for efficiency Union by Rank Heuristic and Path Compression * Update alternate_disjoint_set.py Added typehints, doctests and some suggested variable name change * Update alternate_disjoint_set.py * Formatted with Black * More formatting * Formatting on line 28 * Error in Doctest * Doctest Update in alternate disjoint set * Fixed build error * Fixed doctest
1 parent 5ef7843 commit 1f5134b

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""
2+
Implements a disjoint set using Lists and some added heuristics for efficiency
3+
Union by Rank Heuristic and Path Compression
4+
"""
5+
6+
7+
class DisjointSet:
8+
def __init__(self, set_counts: list) -> None:
9+
"""
10+
Initialize with a list of the number of items in each set
11+
and with rank = 1 for each set
12+
"""
13+
self.set_counts = set_counts
14+
self.max_set = max(set_counts)
15+
num_sets = len(set_counts)
16+
self.ranks = [1] * num_sets
17+
self.parents = list(range(num_sets))
18+
19+
def merge(self, src: int, dst: int) -> bool:
20+
"""
21+
Merge two sets together using Union by rank heuristic
22+
Return True if successful
23+
Merge two disjoint sets
24+
>>> A = DisjointSet([1, 1, 1])
25+
>>> A.merge(1, 2)
26+
True
27+
>>> A.merge(0, 2)
28+
True
29+
>>> A.merge(0, 1)
30+
False
31+
"""
32+
src_parent = self.get_parent(src)
33+
dst_parent = self.get_parent(dst)
34+
35+
if src_parent == dst_parent:
36+
return False
37+
38+
if self.ranks[dst_parent] >= self.ranks[src_parent]:
39+
self.set_counts[dst_parent] += self.set_counts[src_parent]
40+
self.set_counts[src_parent] = 0
41+
self.parents[src_parent] = dst_parent
42+
if self.ranks[dst_parent] == self.ranks[src_parent]:
43+
self.ranks[dst_parent] += 1
44+
joined_set_size = self.set_counts[dst_parent]
45+
else:
46+
self.set_counts[src_parent] += self.set_counts[dst_parent]
47+
self.set_counts[dst_parent] = 0
48+
self.parents[dst_parent] = src_parent
49+
joined_set_size = self.set_counts[src_parent]
50+
51+
self.max_set = max(self.max_set, joined_set_size)
52+
return True
53+
54+
def get_parent(self, disj_set: int) -> int:
55+
"""
56+
Find the Parent of a given set
57+
>>> A = DisjointSet([1, 1, 1])
58+
>>> A.merge(1, 2)
59+
True
60+
>>> A.get_parent(0)
61+
0
62+
>>> A.get_parent(1)
63+
2
64+
"""
65+
if self.parents[disj_set] == disj_set:
66+
return disj_set
67+
self.parents[disj_set] = self.get_parent(self.parents[disj_set])
68+
return self.parents[disj_set]

0 commit comments

Comments
 (0)