Word Cookie Solver

This program will find all of the words that can be made from a specified set of letters.

Setup

First, let's write some code to check if a single word can be made from the letters:


In [1]:
def word_works(letters, word, allow_repeats=False):
    """Return True if word can be spelled using only letters.  letters is a single
    string.  allow_repeats allows each letter to be used many times.
    """
    letters_remaining = letters.lower()  # because dictionary words will be lowercase
    for letter in word:
        if letter in letters_remaining:
            if not allow_repeats:
                letters_remaining = letters_remaining.replace(letter, '', 1)
        else:
            return False
    return True

Then we need a way to check lots of words. We'll need a dictionary:


In [2]:
def load_dict(dict_filename):
    """Load a dictionary file into a list of (lowercase) words."""
    with open(dict_filename) as f:
        content = f.readlines()
    content = [x.strip().lower() for x in content]
    return content

And a way to check all the words in the dictionary:


In [3]:
def match_words(letters, dictionary, allow_repeats=False):
    """Return all words in dictionary that can be spelled using only letters.
    dictionary should be a python list from load_dict().
    """
    results = []
    for word in dictionary:
        if word_works(letters, word, allow_repeats):
            results.append(word)
    return results

Run it

Load the dictionary:


In [4]:
dictionary = load_dict('dictionary.txt')

Specify the letters we can use:


In [5]:
letters = 'wdro'

Find the matches and print them:


In [6]:
matching_words = match_words(letters, dictionary)
print(matching_words)


['do', 'dor', 'dow', 'drow', 'od', 'or', 'ord', 'ow', 'rod', 'row', 'wo', 'word']

We can also sort them with the longest words first:


In [7]:
print( sorted(matching_words, key=len, reverse=True) )


['drow', 'word', 'dor', 'dow', 'ord', 'rod', 'row', 'do', 'od', 'or', 'ow', 'wo']