Skip to content

Instantly share code, notes, and snippets.

@tejinderss
Created October 11, 2017 15:32
Show Gist options
  • Save tejinderss/69caa24d2980d3879113ab3bd0befdb7 to your computer and use it in GitHub Desktop.
Save tejinderss/69caa24d2980d3879113ab3bd0befdb7 to your computer and use it in GitHub Desktop.
import unittest
from collections import defaultdict
class Anagrams(object):
def __init__(self):
self.words = open('words.txt').readlines()
self._load_anagrams()
def _load_anagrams(self):
self.anagrams = defaultdict(list)
for word in self.words:
word = word.strip()
key = "".join(sorted(word))
self.anagrams[key].append(word)
def get_anagrams(self, word):
return self.anagrams["".join(sorted(word))]
class TestAnagrams(unittest.TestCase):
def test_anagrams(self):
anagrams = Anagrams()
self.assertEquals(anagrams.get_anagrams('plates'), ['palest', 'pastel', 'petals', 'plates', 'staple'])
self.assertEquals(anagrams.get_anagrams('eat'), ['ate', 'eat', 'tea'])
def test_anagrams_non_existant(self):
anagrams = Anagrams()
self.assertEquals(anagrams.get_anagrams('nonexistent'), [])
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment