Skip to content

Instantly share code, notes, and snippets.

@fulmicoton
Created September 22, 2014 15:42
Show Gist options
  • Save fulmicoton/ac47aa22f0ac9f46539d to your computer and use it in GitHub Desktop.
Save fulmicoton/ac47aa22f0ac9f46539d to your computer and use it in GitHub Desktop.
from collections import defaultdict
class Trie(object):
__slots__ = ('terminal', 'children')
def __init__(self,):
self.terminal = False
self.children = defaultdict(Trie)
def add(self, word):
if word == "":
self.terminal = True
else:
h, t = word[0], word[1:]
self.children[h].add(t)
def __item__(self, l):
return self.children[l]
ENGLISH = Trie()
with open("/usr/share/dict/american-english") as f:
for l in f:
ENGLISH.add(l.strip())
def find_anagram(w, dic=ENGLISH):
if len(w) == 0 and dic.terminal:
yield ""
else:
for rank in range(len(w)):
l = w[rank]
if l in dic.children:
for perm in find_anagram(w[:rank] + w[rank + 1:], dic.children[l]):
yield l + perm
for w in find_anagram("clement"):
print w
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment