Created
April 16, 2017 18:03
-
-
Save jsbueno/585b628cac1b743433f5ed687f2bbaa7 to your computer and use it in GitHub Desktop.
Python3 Disjoint Set imlementation
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
from collections.abc import MutableMapping | |
class DisjointSet(MutableMapping): | |
"""Working disjoint set implementatin in Python - | |
check https://en.wikipedia.org/wiki/Disjoint-set_data_structure | |
""" | |
def __init__(self, initial): | |
self.data = dict() | |
self.index = dict() | |
for item in initial: | |
self.add(item) | |
def add(self, item): | |
if not item in self: | |
# Create a new singleton subset | |
self.data[item] = item | |
self.index[item] = {item,} | |
def __getitem__(self, item): | |
return self.data[item] | |
def __setitem__(self, item, value): | |
raise NotImplementedError("Use 'add' to add new elements") | |
def __delitem__(self, item): | |
raise NotImplementedError("Not implemented") | |
def __iter__(self): | |
yield from self.data | |
def __len__(self): | |
return len(self.data) | |
find = __getitem__ | |
def join(self, key1, key2): | |
if len(self.index[key1]) > len(self.index[key2]): | |
source = key2; target = key1 | |
else: | |
source = key1; target = key2 | |
for item in self.index[source]: | |
self.index[target].add(item) | |
self.data[item] = target | |
del self.index[source] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment