Problem Set 5; problem 2 of 6
You will now write a function that takes a hand and a word as inputs, uses letters from that hand to
spell the word, and returns the remaining letters in the hand. This function will return True if the word is in the word_list and is entirely composed of letters in the hand. Otherwise, the function returns False. The function also does not mutate hand or word_list.
The part that was the most difficult for this problem, was re-learning why I needed to make sure the original hand inputted was not altered, and how to do it. I remembered that there was a copy function but I honestly couldn’t remember how to use it. Once I got that done, it was only a question of using one of the created functions in the problem set (get_frequency_dict(word), which takes a word and returns a dictionary with each letter being the key to the frequency in which that letter occurred). Then I used that dictionary it created and went through each key (letter), by using a for loop. Here is my function below.
def update_hand(hand, word): newlist = get_frequency_dict(word) newhand = hand.copy() for letter in newlist: if newhand[letter] > 1: newhand[letter] = newhand[letter] - 1 elif newhand[letter] == 1: del newhand[letter] return newhand |
First I assign newlist to a function that creates a dictionary out of the variable word. Then I create a copy of the hand, so that I don’t alter it during the processing of the function. I do this by using the copy() function to process it. Next I institute a for loop, where I go through each letter in the newlist dictionary. The beginning of the for loop asks the following: if there is a letter that matches the newlist letter, and its key is greater than one, then the function is to subtract one from the key. If the key is equal to one, then it is simply deleted from the list. Once all letters have been processed through the for loop, the end result will be a dictionary that only includes letters that are not used in the word submitted.
The important factor, is that the information that is spit out of this function is not altering some of the information used to create it, because I copied it. The other important part is that this function can take into account when a player has two or more of the same kind of letter in their hand. That part was something I realized after most of the problem was finished. So I had to go back and put in the bit of code that subtracts one from from the key. Before I had simply been deleting it if it showed up in newlist. Now THAT was not providing accurate data.
Up Next: More Python Love