Skip to content

Instantly share code, notes, and snippets.

@ijkilchenko
Last active March 7, 2022 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijkilchenko/c24d6ff8f926cff1924618d9e22395e2 to your computer and use it in GitHub Desktop.
Save ijkilchenko/c24d6ff8f926cff1924618d9e22395e2 to your computer and use it in GitHub Desktop.
bananagrams_completer
from itertools import combinations
from collections import defaultdict, Counter
def to_multiset(word):
return frozenset(Counter(word).items())
def find_longer_words(dictionary, words):
for num_words in range(2, min(len(words), 10)):
print()
print('Checking combinations of length %i' % num_words)
for combination in combinations(enumerate(words), num_words):
old_words = [value for key, value in combination]
joined = ''.join(old_words)
if to_multiset(joined) in dictionary:
new_words = dictionary[to_multiset(joined)]
move = '%s from %s' % (new_words, old_words)
print(move)
print()
if __name__ == '__main__':
# Dictionary file:
# Other possible dictionary file:
# http://www.gwicks.net/dictionaries.htm
# https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt
# /usr/share/dict/words
# Filter dictionary file by word length and put all words into a set
with open('/usr/share/dict/words') as file:
lines = file.read().splitlines()
lines = filter(lambda word: len(word) >= 3, lines)
dictionary = {word: frozenset(to_multiset(word)) for word in lines} # Values are a set of the word with multiplicity
# Create a backwards mapping, from the set of letters back to all words you can make from those letters.
inv_dictionary = defaultdict(lambda : [])
for word, multiset_from_word in dictionary.items():
inv_dictionary[multiset_from_word].append(word)
words = 'truth,reek,kite,wade,main,zap,strays,honey,blimp,feet,grabs,devote,jinx,gravy,induct,fog,lion,cruel,amuse,pointe,fade,ozone,woe,avoid,wax,trialed,sluice,hoarse,baring,q,j,i,o,u,q'.split(',')
find_longer_words(inv_dictionary, words)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment