ps3a Problem 3 help needed. How do I compare dictionaries if there is no order? here is the link to the problem set: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/unit-1/lecture-7-debugging/MIT6_00SCS11_ps3.pdf I see that there are two parts to this question- 1. Must test if word is in word_list 2. If the letters in word are in hand I solve the first by the first if/else pair but am stuck with the second part. Here are some approaches I have tried: Approach 1: ref=('hello', 'bye', 'butts', 'helllo') hand={'h':2, 'e':1, 'l':2, 'o':1} def is_valid_word(word, hand, word_list): """ Returns True if word is in the word_list and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or word_list. word: string hand: dictionary (string -> int) word_list: list of lowercase strings """ # TO DO... if word in word_list: for letter in word: hand[letter]-=1 #print hand if hand[letter]>=0: return True else: return False else: return False #print is_valid_word('hello', hand, ref) print is_valid_word('helllo', hand, ref) #print is_valid_word('bye', hand, ref) In this approach I attempt to mutate the dictionary hand so that for each letter in word the value associated with the key (letter in word) is reduced by 1. Then, I attempt to test if the new value in hand is >= 0 (the idea being if it is >=0 then there are enough letters in the hand). Approach 2: I wont post the code, but essentially I was attempting to turn the word played into a dictionary using the provided function. At this point, I was unsure how to proceed as I don't know how to compare dicts since they are not ordered like lists. I thought about converting both hand and the dict derived from word to lists then comparing but couldn't figure out how. Thanks for the help!
If you want to compare dictionaries, iterate through the keys in one, and as long as the second one.has_key( <key> ), they're matching.
?
Join our real-time social learning platform and learn together with your friends!