Skip to content

Instantly share code, notes, and snippets.

@gvoysey
Last active October 28, 2018 19:30
Show Gist options
  • Select an option

  • Save gvoysey/4f3a0d387d79519067a231886c284ae0 to your computer and use it in GitHub Desktop.

Select an option

Save gvoysey/4f3a0d387d79519067a231886c284ae0 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
from collections import defaultdict
def words(words_file):
"""Return one word at a time from a potentially very large list of words."""
with open(words_file, 'r') as f:
for line in f:
# give back one word at a time, with no whitespace, and converted to
# lowercase.
yield line.casefold().strip()
def anagram(word_generator):
"""Words are anagrams if you get the same string if you sort their characters alphabetically.
"""
anagrams = defaultdict(list)
for word in iter(word_generator()):
anagrams[''.join(sorted(word))].append(word)
# return the lists that have more than one element -- ie an anagram was found.
return [v for v in anagrams.values() if len(v)>1]
for anagram in anagram(words('words.txt')):
print(','.join(anagram))
print(f'{len(anagrams)} anagrams found')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment