Skip to content

Commit f9b6a8c

Browse files
authored
Implement find_size for disjoint set union data structure (#516)
1 parent 8f419fd commit f9b6a8c

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

pydatastructs/miscellaneous_data_structures/disjoint_set.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,12 @@ def make_root(self, key):
115115
key_set.size = all_set_size
116116
# Make parent of key as itself
117117
key_set.parent = key_set
118+
119+
def find_size(self, key):
120+
"""
121+
Finds the size of set to which the key belongs.
122+
"""
123+
if self.tree.get(key, None) is None:
124+
raise KeyError("Invalid key, %s"%(key))
125+
126+
return self.find_root(key).size

pydatastructs/miscellaneous_data_structures/tests/test_disjoint_set.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,19 @@ def test_DisjointSetForest():
99

1010
dst.union(1, 2)
1111
dst.union(1, 5)
12+
assert dst.find_size(2) == 3
1213
dst.union(1, 6)
1314
dst.union(1, 8)
1415
dst.union(3, 4)
16+
assert dst.find_size(3) == 2
1517

1618
assert (dst.find_root(1) == dst.find_root(2) ==
1719
dst.find_root(5) == dst.find_root(6) == dst.find_root(8))
1820
assert dst.find_root(3) == dst.find_root(4)
1921
assert dst.find_root(7).key == 7
2022

2123
assert raises(KeyError, lambda: dst.find_root(9))
24+
assert raises(KeyError, lambda: dst.find_size(9))
2225
dst.union(3, 1)
2326
assert dst.find_root(3).key == 1
2427
assert dst.find_root(5).key == 1

0 commit comments

Comments
 (0)