Skip to content

Commit e0b1c99

Browse files
committed
add make_root method
1 parent a21d00e commit e0b1c99

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

pydatastructs/miscellaneous_data_structures/disjoint_set.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ class DisjointSetForest(object):
1616
>>> dst.union(1, 2)
1717
>>> dst.find_root(2).key
1818
1
19+
>>> dst.make_root(2)
20+
>>> dst.find_root(2).key
21+
2
1922
2023
References
2124
==========
@@ -74,3 +77,18 @@ def union(self, key1, key2):
7477

7578
y_root.parent = x_root
7679
x_root.size += y_root.size
80+
81+
def make_root(self, key):
82+
"""
83+
Finds the set to which the key belongs
84+
and makes it as the root of the set.
85+
"""
86+
if self.tree.get(key, None) is None:
87+
raise KeyError("Invalid key, %s"%(key))
88+
89+
current_root = self.find_root(key)
90+
if current_root.key != key:
91+
key_set = self.tree[key]
92+
current_root.parent = key_set
93+
key_set.size = current_root.size
94+
key_set.parent = key_set

pydatastructs/miscellaneous_data_structures/tests/test_disjoint_set.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,15 @@ def test_DisjointSetForest():
1515

1616
assert (dst.find_root(1) == dst.find_root(2) ==
1717
dst.find_root(5) == dst.find_root(6) == dst.find_root(8))
18+
assert dst.find_root(1).key == 1
19+
assert dst.find_root(2).key == 1
20+
dst.make_root(8)
21+
assert dst.find_root(2).key == 8
22+
assert dst.find_root(8).key == 8
1823
assert dst.find_root(3) == dst.find_root(4)
1924
assert dst.find_root(7).key == 7
20-
25+
dst.make_root(2)
2126
assert raises(KeyError, lambda: dst.find_root(9))
27+
assert raises(KeyError, lambda: dst.make_root(19))
2228
dst.union(3, 1)
23-
assert dst.find_root(3).key == 1
29+
assert dst.find_root(3).key == 2

0 commit comments

Comments
 (0)