Created
October 9, 2021 18:43
-
-
Save tylerneylon/f24e6058143c5c9ea1a942e89ddd9693 to your computer and use it in GitHub Desktop.
A short Python script to print out anagrams.
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
#!/usr/bin/env python3 | |
""" anagrams.py | |
Usage: | |
./anagrams.py myword | |
Prints out a list of anagrams of myword. | |
This uses the file /usr/share/dict/words to get a dictionary. | |
""" | |
# ______________________________________________________________________ | |
# Imports | |
import sys | |
from collections import defaultdict | |
# ______________________________________________________________________ | |
# Functions | |
def load_wordmap(): | |
""" Load all words and map their sorted string to a list of all the words | |
that sort to that key. Eg 'aemt' -> ['meat', 'team', ...]. | |
""" | |
with open('/usr/share/dict/words') as f: | |
wordlist = [line.strip() for line in f if len(line.strip()) > 0] | |
# Add approximate plurals. | |
plurals = [x + 's' if not x.endswith('s') else x + 'es' for x in wordlist] | |
wordlist += plurals | |
wordmap = defaultdict(list) | |
for word in wordlist: | |
wordmap[''.join(sorted(word))].append(word) | |
return wordmap | |
def print_anagrams(wordmap, word): | |
""" Using `wordmap`, print all the anagrams of `word`. """ | |
for other_word in wordmap[''.join(sorted(word))]: | |
print(other_word) | |
# ______________________________________________________________________ | |
# Main | |
if __name__ == '__main__': | |
if len(sys.argv) == 1: | |
print(__doc__) | |
sys.exit(0) | |
wordmap = load_wordmap() | |
print_anagrams(wordmap, sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment