Last active
January 18, 2019 21:40
-
-
Save Gumnos/309726ab70889f7f0289b0d9aa8dbfef to your computer and use it in GitHub Desktop.
Find words in a dictionary that can be deconstructed one letter at a time while still making words from that dictionary
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 sys import argv | |
from string import ascii_lowercase | |
lowercase = frozenset(ascii_lowercase) | |
if len(argv) > 1: | |
dictionary_name = argv[1] | |
else: | |
dictionary_name = "/usr/share/dict/words" | |
dictionary = frozenset( | |
word.rstrip() | |
for word in file(dictionary_name) | |
if lowercase.issuperset(word.rstrip()) | |
) | |
def test_word(word, candidates): | |
if len(word) < 2: | |
if word in "ia": # only interested in final 1-letter words "I" and "A" | |
yield [] | |
else: | |
for i in range(len(word)): | |
check_word = word[:i] + word[i+1:] | |
if check_word in candidates: | |
for smaller_matches in test_word(check_word, candidates): | |
yield [check_word] + smaller_matches | |
maxlen = 5 # default to something low | |
longest_chains = set() | |
for word in dictionary: | |
if len(word) < maxlen: continue # don't look at lesser words | |
for results in test_word(word, dictionary): | |
results = [word] + results | |
new_maxlen = len(results) | |
if new_maxlen > maxlen: | |
maxlen = new_maxlen | |
longest_chains = set([tuple([word] + results)]) | |
elif new_maxlen == maxlen: | |
longest_chains.add(tuple(results)) | |
for result in sorted(longest_chains): | |
print("%i: %s" % ( | |
len(result), | |
' '.join(w.upper() for w in result), | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment