Created
August 19, 2012 22:20
-
-
Save hernantz/3398182 to your computer and use it in GitHub Desktop.
These files are the python implementation of the union find algoritm and it's unit tests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import unittest | |
from union_find import UnionFind | |
class TestUnionFind(unittest.TestCase): | |
def test_init(self): | |
u = UnionFind(5) | |
self.assertEquals([0, 1, 2, 3, 4], u.id) | |
def test_connected(self): | |
u = UnionFind(5) | |
u.id[1] = u.id[2] | |
self.assertTrue(u.connected(1, 2)) | |
self.assertTrue(u.connected(2, 1)) | |
self.assertTrue(u.connected(2, 2)) | |
self.assertTrue(u.connected(1, 1)) | |
def test_not_connected(self): | |
u = UnionFind(5) | |
self.assertFalse(u.connected(1, 2)) | |
def test_union(self): | |
u = UnionFind(5) | |
u.union(1, 2) | |
self.assertEquals(u.id[1], u.id[1]) | |
self.assertEquals(u.id[1], u.id[2]) | |
self.assertEquals(u.id[2], u.id[1]) | |
if __name__ == '__main__': | |
unittest.main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
class UnionFind(): | |
def __init__(self, size): | |
self.id = [i for i in xrange(size)] | |
def connected(self, a, b): | |
return self.id[a] == self.id[b] | |
def union(self, a, b): | |
first = self.id[a] | |
second = self.id[b] | |
for i in self.id: | |
if self.id[i] == first: | |
self.id[i] = second |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment