Skip to content

Commit 1aa53bf

Browse files
authored
Implement disjoint_sets method in DisjointSetForest (#521)
1 parent 93e01b0 commit 1aa53bf

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

pydatastructs/miscellaneous_data_structures/disjoint_set.py

+17
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,20 @@ def find_size(self, key):
124124
raise KeyError("Invalid key, %s"%(key))
125125

126126
return self.find_root(key).size
127+
128+
def disjoint_sets(self):
129+
"""
130+
Returns a list of disjoint sets in the data structure.
131+
"""
132+
result = dict()
133+
for key in self.tree.keys():
134+
parent = self.find_root(key).key
135+
members = result.get(parent, [])
136+
members.append(key)
137+
result[parent] = members
138+
sorted_groups = []
139+
for v in result.values():
140+
sorted_groups.append(v)
141+
sorted_groups[-1].sort()
142+
sorted_groups.sort()
143+
return sorted_groups

pydatastructs/miscellaneous_data_structures/tests/test_disjoint_set.py

+3
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ def test_DisjointSetForest():
1717

1818
assert (dst.find_root(1) == dst.find_root(2) ==
1919
dst.find_root(5) == dst.find_root(6) == dst.find_root(8))
20+
assert dst.disjoint_sets() == [[1, 2, 5, 6, 8], [3, 4], [7]]
2021
assert dst.find_root(3) == dst.find_root(4)
2122
assert dst.find_root(7).key == 7
2223

@@ -26,6 +27,7 @@ def test_DisjointSetForest():
2627
assert dst.find_root(3).key == 1
2728
assert dst.find_root(5).key == 1
2829
dst.make_root(6)
30+
assert dst.disjoint_sets() == [[1, 2, 3, 4, 5, 6, 8], [7]]
2931
assert dst.find_root(3).key == 6
3032
assert dst.find_root(5).key == 6
3133
dst.make_root(5)
@@ -42,6 +44,7 @@ def test_DisjointSetForest():
4244
assert dst.tree[3].size == 1
4345
dst.union(1, 4)
4446
dst.union(2, 4)
47+
assert dst.disjoint_sets() == [[0], [1, 2, 3, 4], [5]]
4548
# current tree
4649
###############
4750
# 2

0 commit comments

Comments
 (0)