Skip to content

Instantly share code, notes, and snippets.

@rafiamafia
Created April 19, 2018 21:48
Show Gist options
  • Save rafiamafia/f84ffb65220ff3aeee3707b0310cb1d9 to your computer and use it in GitHub Desktop.
Save rafiamafia/f84ffb65220ff3aeee3707b0310cb1d9 to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, data):
self.data = data
self.parent = self
self.rank = 0
class DisjointSet:
def __init__(self):
self.map = {}
def makeSet(self, data):
self.map[data] = Node(data)
def findSet(self, data):
if not self.map.get(data):
raise ValueError('{} is not in the DisjointSet'.format(data))
return self._find(self.map.get(data)).data
def _find(self, node):
if node.parent == node:
return node.parent
node.parent = self._find(node.parent)
return node.parent
def union(self, data1, data2):
node1 = self.map.get(data1)
node2 = self.map.get(data2)
if node1.parent.data == node2.parent.data:
return False
if node1.parent.rank >= node2.parent.rank:
node1.parent.rank = node1.parent.rank + 1 if node1.parent.rank == node2.parent.rank else node1.parent.rank
node2.parent = node1.parent
else:
node1.parent = node2.parent
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment