Skip to content

Instantly share code, notes, and snippets.

@sumoward
Created February 21, 2017 10:29
Show Gist options
  • Save sumoward/c3d9f4613e782b6bd8f8e38b30b5df0d to your computer and use it in GitHub Desktop.
Save sumoward/c3d9f4613e782b6bd8f8e38b30b5df0d to your computer and use it in GitHub Desktop.
test for anagagrams in a list of strings
from collections import defaultdict
def load_words(filename='/usr/share/dict/american-english'):
with open(filename) as f:
for word in f:
yield word.rstrip()
def get_anagrams(source):
d = defaultdict(list)
for word in source:
key = "".join(sorted(word))
d[key].append(word)
return d
def print_anagrams(word_source):
d = get_anagrams(word_source)
for key, anagrams in d.iteritems():
if len(anagrams) > 1:
print(key, anagrams)
# word_source = load_words()
word_source = ["car", "tree", "boy", "girl", "arc", "sarcocarcinomata", "carcinosarcomata"]
print_anagrams(word_source)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment