liveBook · Manning

Tile

As explained in Get Programming: Learn to code with Python

A tile is a game piece bearing a letter that can be combined with other letter tiles to form words.

A tile is a game piece bearing one letter. Given several tiles, the goal is to find every valid art-related word you can spell with them. The number of tiles can vary, and no letter has a point value. section 19.0

A program can solve the problem in three steps:

  • Store the tiles as a string, such as `tiles = "hijklmnop"`. section 19.0
  • Separate the newline-delimited valid words into a tuple so each word can be checked on its own. section 19.1
  • For each word, check its letters against a fresh copy of the tile string. Remove each tile as it is used, so one tile cannot supply the same letter twice. section 19.1 section 19.2
Listing 19.3. Game code to check whether valid words can be made with tiles
for word in all_valid_words:                                            #1
    tiles_left = tiles                                                  #2
    for letter in word:                                                 #3
        if letter not in tiles_left:                                    #4
            break                                                       #4
        else:
            index = tiles_left.find(letter)                             #5
            tiles_left = tiles_left[:index]+tiles_left[index+1:]        #6
    if len(word) == len(tiles)-len(tiles_left):                         #7
        found_words = found_words + (word,)                             #8
print(found_words)

Notice that `tiles_left` starts over for each word. When a letter is found, slicing removes that occurrence; if a letter is missing, the loop stops. The final length check determines whether to add the word to `found_words`. section 19.2

A set of tiles

With `tiles = "hijklmnop"`, possible reported words include `('ink', 'oil', 'kiln')`. Each word is checked against the original set of tiles, not against the tiles left after checking a previous word. section 19.0 section 19.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Works through tile matching in pseudocode and Python, including repeated letters; leaves out letter scores.
Examples
Checks `tiles = "hijklmnop"` against art-related words and shows a tuple containing `ink`, `oil`, and `kiln`.
What it assumes
Builds on conditionals and loops while showing how to plan the problem and use a multiline string.
What you can do after
Build it from scratch: write a Python program that reports valid words constructible from a given tile string.
How it connects
Connects tiles to strings, tuples, loops, conditionals, and string slicing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.