Created
January 18, 2019 16:49
-
-
Save alexgolec/fdfaf857150109ec333d48159cdd2a10 to your computer and use it in GitHub Desktop.
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
class DisjointSet(object): | |
def __init__(self): | |
self.parents = {} | |
def get_root(self, w): | |
words_traversed = [] | |
while self.parents[w] != w: | |
words_traversed.append(w) | |
w = self.parents[w] | |
for word in words_traversed: | |
self.parents[word] = w | |
return w | |
def add_synonyms(self, w1, w2): | |
if w1 not in self.parents: | |
self.parents[w1] = w1 | |
if w2 not in self.parents: | |
self.parents[w2] = w2 | |
w1_root = self.get_root(w1) | |
w2_root = self.get_root(w2) | |
if w1_root < w2_root: | |
w1_root, w2_root = w2_root, w1_root | |
self.parents[w2_root] = w1_root | |
def are_synonymous(self, w1, w2): | |
return self.get_root(w1) == self.get_root(w2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment