Problem Set 5; problem 3 of 6
This function should return True if the word is in the word_list and is entirely composed of letters in the hand. Otherwise, it returns False. This function should not mutate the hand or word_list.
Like I mentioned above, this problem is fairly simply. The implementation is fairly simple, there was only one real hump I had to get over. One that I’m still working on. Understanding how get() works. Get() is a function one can use on dictionaries (a method of dictionaries, if you want to get technical). As described on docs.python.org, it; returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. To better explain, here is an example dictionary:
hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
Hand is the name of the dictionary. A key is the letters, such as ‘a’, or ‘m’. The value is the frequency in which the letters occur in the hand, or the number listed next to each letter (key). To use get(), one could simply type print hand.get(‘a’,0), and you would get the number 1 printed in the next line. If the letter you were looking for did not exist in the dictionary it would return ‘0’. Learning how to use get() was very useful, as it simplified my function greatly.
def is_valid_word(word, hand, word_list): newlist = get_frequency_dict(word) newhand = hand.copy() if word in word_list: for letter in newlist: if newhand.get(letter,0) < newlist[letter]: return False return True else: return False |
Up Next: More Python Love