Created
October 20, 2020 23:46
-
-
Save reynoldscem/248739d8d058ae38b5434f3208095569 to your computer and use it in GitHub Desktop.
Find whole word anagrams from word list.
This file contains hidden or 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 argparse import ArgumentParser | |
from collections import defaultdict | |
from pathlib import Path | |
def build_parser(): | |
parser = ArgumentParser() | |
parser.add_argument('wordlist_filename', type=Path) | |
return parser | |
def load_wordlist(filename): | |
with open(filename) as fd: | |
data = fd.read().lower().splitlines() | |
return set(data) | |
def main(): | |
args = build_parser().parse_args() | |
wordlist = load_wordlist(args.wordlist_filename) | |
anagram_table = defaultdict(set) | |
for word in wordlist: | |
anagram_table[''.join(sorted(word))].add(word) | |
while True: | |
line = input("Enter a word to find anagrams for: ").strip() | |
key = ''.join(sorted(line.lower())) | |
matches = anagram_table[key] - {line.lower()} | |
if not matches: | |
print("No matches!") | |
continue | |
for match in matches: | |
print(match) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment