This function returns the score for a word. It assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, plus 50 points if all n letters are used on the first go. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. The dictionary with letters and subsequent values are provided.
It took me about 4 hours to solve this problem. The first day I was convinced that the way to solve it was by making the word into a list, and then comparing the lists. Thankfully I had a days break before I revisited my work, and realized there was a much simpler way to do it. Here is my function.
|def get_word_score(word, n):
total = 0
for letter in word:
total += SCRABBLE_LETTER_VALUES [letter]
if len (word) == n:
total = total + 50
In this function there are two variables. The first is a word (a string), that is entered. The second is n, which is a value for the total amount of letters in the players hand. This total amount can change, thus it was entered as a variable.
To start my function off I begin by assigning (designating) total to zero. I know I need to go through each letter in the word I’ve been given, and figure out what each letter is valued at. Easiest way to do that is a for loop. So I go through each letter in my word, and compare it to the keys in the dictionary to find the value associated with each letter. I then add them up as I go, which also means I’m not missing any repeat letters. If I had compared the lists in some way, I might have come up with some errors because of multiple occurrences of the same letter in a word.
There isn’t much else to this function, except verifying if the word is using up all the letters in the players hand. That’s done by verifying the length of the word against the variable n. If it is, then I simply add 50 points to the total value of total. Once all items have been processed I simply pop out the value of total at the end of the function. Dictionaries are very, very useful.