Created
February 21, 2017 10:29
-
-
Save sumoward/c3d9f4613e782b6bd8f8e38b30b5df0d to your computer and use it in GitHub Desktop.
test for anagagrams in a list of strings
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 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