Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 21c1855

Browse files
committed
change union find class to make it follow oop encapsulation property
1 parent 55ece64 commit 21c1855

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

algorithms/data_structure/union_find.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,32 +18,32 @@ def __init__(self, N):
1818
raise TypeError, "size must be integer"
1919
if N < 0:
2020
raise ValueError, "N cannot be a negative integer"
21-
self.forests = []
22-
self.N = N
21+
self.__parent = []
22+
self.__N = N
2323
for i in range(0, N):
24-
self.forests.append(i)
24+
self.__parent.append(i)
2525

2626
def make_set(self, x):
2727
if type(x) != int:
2828
raise TypeError, "x must be integer"
29-
if x != self.N:
30-
raise ValueError, "a new element must have index {0} since the total num of elements is {0}".format(self.N)
31-
self.forests.append(x)
32-
self.N = self.N + 1
29+
if x != self.__N:
30+
raise ValueError, "a new element must have index {0} since the total num of elements is {0}".format(self.__N)
31+
self.__parent.append(x)
32+
self.__N = self.__N + 1
3333

3434
def union(self, x, y):
3535
self.__validate_ele(x)
3636
self.__validate_ele(y)
3737
x_root = self.find(x)
3838
y_root = self.find(y)
39-
self.forests[x_root] = y_root
39+
self.__parent[x_root] = y_root
4040

4141
def find(self, x):
4242
self.__validate_ele(x)
43-
if self.forests[x] == x:
43+
if self.__parent[x] == x:
4444
return x
4545
else:
46-
return self.find(self.forests[x])
46+
return self.find(self.__parent[x])
4747

4848
def is_connected(self, x, y):
4949
self.__validate_ele(x)
@@ -53,5 +53,5 @@ def is_connected(self, x, y):
5353
def __validate_ele(self, x):
5454
if type(x) != int:
5555
raise TypeError, "{0} is not an integer".format(x)
56-
if x < 0 or x >= self.N:
57-
raise ValueError, "{0} is not in [0,{1})".format(x, self.N)
56+
if x < 0 or x >= self.__N:
57+
raise ValueError, "{0} is not in [0,{1})".format(x, self.__N)

0 commit comments

Comments
 (0)