Skip to content
scipython.com

P2.7.1Does a Scrabble word fit?

The word game Scrabble is played on a \(15 \times 15\) grid of squares referred to by a row index letter (A - O) and a column index number (1 - 15). Write a function to determine whether a word will fit in the grid, given the position of its first letter as a string (for example, 'G7') a variable indicating whether the word is placed to read across or down the grid and the word itself.

Show solution

The function defined below generates a starting position, \(i\), for the word in the range (1 - 15) along either a row or column as specified by the boolean variable across. The word only fits in the grid if its length is less than or equal to \(16-i\).

def word_fits(word, position, across):
    """ Determine if a given word fits in a scrabble grid.

    Given a word and starting position, determine whether the word fits
    within the standard Scrabble grid. The position is specified as a string
    giving the grid reference as a row letter (A-O) followed by a column
    number (1-15); across is True if the word is to be placed along a row and
    False if it is to be placed down a column from the starting position.

    """

    if across:
        # Get the starting column position (starting at 1)
        i = int(position[1:])
    else:
        # Get the starting row position (starting at 'A'=1)
        i = ord(position[0]) - 64   # NB ord('A') is 65 ... ord('O') is 79

    return len(word) <= 16 - i

def report(word, position, across):
    across_down = 'across' if across else 'down'
    mod = 'not' if not word_fits(word, position, across) else ''
    return '"{}" {} at {} does {} fit'.format(word, across_down, position, mod)


print(report('HELLO', 'I2', across=False))
print(report('HELLO', 'J2', across=False))
print(report('HELLO', 'K2', across=False))
print(report('HELLO', 'L2', across=False))
print(report('HELLO', 'M2', across=False))
print(report('HELLO', 'N2', across=False))
print(report('HELLO', 'O2', across=False))
print(report('LO', 'A12', across=True))
print(report('LO', 'A13', across=True))
print(report('LO', 'A14', across=True))
print(report('LO', 'A15', across=True))

The output:

"HELLO" down at I2 does  fit
"HELLO" down at J2 does  fit
"HELLO" down at K2 does  fit
"HELLO" down at L2 does not fit
"HELLO" down at M2 does not fit
"HELLO" down at N2 does not fit
"HELLO" down at O2 does not fit
"LO" across at A12 does  fit
"LO" across at A13 does  fit
"LO" across at A14 does  fit
"LO" across at A15 does not fit