6.65 Scrabble: Part 4
Before you begin
Important: This is Part 4 of the Scrabble lab, the final part that ties everything together. Make sure you have completed Parts 1, 2, and 3 first. Copy your implementations of the following functions and paste them in the indicated spots below: is_valid (Part 1), get_playable_words (Part 2), and word_score (Part 3).
Part 4: Highest scoring word
In this final assignment, you will write a function called highest_scoring_word which takes as input a list of uppercase letters (strings) representing a Scrabble hand and determines the highest scoring word that can be spelled. Your function should return a 2-element tuple containing the word followed by its score. (If there is a tie for the highest score, you may break the tie in any way you like.)
If the input to your highest_scoring_word function is the list of letters ["E","O","O","N","Z","T"], then the function should return ("OZONE", 14). Since this is the highest scoring word that can be played from the given tiles and its score. If no word can be made, you should return ("", 0).
In your implementation of the highest_scoring_word function, you should call the get_playable_words function to get a set of all possible words. Then you should call the word_score function on each word to determine its score.
1 from itertools import permutations
2
3 VALID_WORDS = open("scrabble_wordlist.txt").read().splitlines()
4
5 LETTER_SCORES = {
6 "A": 1, "B": 3, "C": 3,
7 "D": 2, "E": 1, "F": 4,
8 "G": 2, "H": 4, "I": 1,
9 "J": 8, "K": 5, "L": 1,
10 "M": 3, "N": 1, "O": 1,
11 "P": 3, "Q": 10, "R": 1,
12 "S": 1, "T": 1, "U": 1,
13 "V": 4, "W": 4, "X": 8,
14 "Y": 4, "Z": 10
15 }
16
17 VALID_WORDS = set(word.strip().upper() for word in open('scrabble_wordlist.txt'))
18
19 def is_valid(word):
20 return word.upper() in VALID_WORDS
21
22 def get_playable_words(rack):
23 playable_words = set()
24 for i in range(1, len(rack) + 1): # check all possible word lengths
25 for perm in permutations(rack, i):
26 word = "".join(perm)
27 if is_valid(word, rack):
28 playable_words.add(word)
29 return playable_words
30
31 def word_score(word):
32 letter_scores = {
33 'A': 1, 'E': 1, 'I': 1, 'O': 1, 'U': 1, 'L': 1, 'N': 1, 'S': 1, 'T': 1, 'R': 1,
34 'D': 2, 'G': 2, 'B': 3, 'C': 3, 'M': 3, 'P': 3,
35 'F': 4, 'H': 4, 'V': 4, 'W': 4, 'Y': 4,
36 'K': 5,
37 'X': 8,
38 'Z': 10
39 }
40
41 score = 0
42 for letter in word:
43 score += letter_scores[letter]
44
45 return score