New York Times Spelling Bee solver

(1 comment)

The New York Times publishes a daily puzzle, Spelling Bee, in which players must find as many words as possible using seven letters arranged in a hexagon. Each letter may be used any number of times but the solution words must be at least four letters long and must include the letter at the centre of the hexagon.

NYT Spelling Bee from 29/11/22

For example, in the above puzzle, valid solution words are "CINEMA" and "AMBIENCE" but not "ACE" (not enough letters) or "BEANIE" (no central letter, "C").

The code below finds the solution words from the puzzle letters provided as a command line argument with the central letter first. For example,

$ python spellingbee.py CBIEMNA

The word list used is the Collins Scrabble Word list, SOWPODS, provided here: sowpods. On Unix-like systems, you could, as an alternative, use the built-in /usr/share/dict/words word list, but this one is old, of doubtful provenance, and has some odd omissions (e.g. "women" is not in it...)

import sys

# Some possible word lists to search:
# /usr/share/dict/words is available on most Unix-like systems:
#wordlist_filename = '/usr/share/dict/words'
# Better is the Collins Scrabble Word list, SOWPODS:
wordlist_filename = './sowpods'

def get_words():
    """Read the provided word list and convert to upper case."""

    with open(wordlist_filename) as fi:
        words = [word.strip().upper() for word in fi]
    return words

def solve_spellingbee(letters, min_length=4):
    """Solve the Spelling Bee.

    letters is a string of the letters to solve for, with the central letter,
    which must be in every solution word first.

    """

    central_letter = letters[0]
    letter_set = set(letters)
    words = get_words()

    valid_words = []
    for word in words:
        if len(word) < min_length:
            continue
        if central_letter not in word:
            continue
        if set(word).issubset(letter_set):
            valid_words.append(word)
    print(f'{len(valid_words)} matching words found:')

    # Print the solution words, sorted by length and, within each word length,
    # sorted alphabetically.
    for valid_word in sorted(valid_words, key=lambda word: (len(word), word)):
        print(valid_word)

if __name__ == '__main__':
    letters = sys.argv[1]
    assert len(letters) == 7
    solve_spellingbee(letters)

For example:

$ python spellingbee.py EXLINGC
99 matching words found:
CEIL
CELL
CIEL
CINE
CLEG
...
LICENCING
EXCELLENCE
NEGLIGENCE
Current rating: 4.5

Comments

Comments are pre-moderated. Please be patient and your comment will appear soon.

Paco 1 year, 8 months ago

Hi.
I didn't know there was a set(), set().issubset() or assert.
Neither did I know there was word list (incomplete though) in Linux. Mine in Mint looks different but I found it.
Nice example. Thank you.

Link | Reply
Currently unrated

New Comment

required

required (not published)

optional

required