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
