In ps5, the display_hand function utilizes two for loops. Can someone explain the need for the second loop? for j in range(hand[letter]): Thanks!
That's a good question. The 'hand' variable is a dictionary representing the number of each letters in a hand. It might help to remember that the number of items in the dictionary will change with the number of repeated letters. For instance, if a hand consists of 5 letters, the dictionary can have between one item hand = {'a':5,} and 5 items hand = {'a':1, 'b':1, 'c':1, "d':1, 'e':1} Both of those dicts represent the same number of letters, but one represents 5 a's, while the other represents 1 each of a b c d e. When you 'call' the letter, for instance hand['a'], you get the value associated with that number in the dict. So in the first dict, you'd get 5, and in the second dict you'd get 1. What the first 'for' loop does is it says 'iterate over all the keys in the hand dict'. So the first thing 'letter' represents is 'a', and in the second dict, the second thing it represents is 'b', and so on. the second for loop is what prints the actual letters. It uses a range specified by the value 'half' of the current key in the hand dict. So using the first dict: for j in range(hand[letter]): resolves to for j in range(hand['a']): hand['a'], in that definition, equals 5, because 5 is the 'value' half of the key 'a'. so we're left with: for j in range(5): print letter which prints the current letter 'a' 5 times. does that make sense?
Makes perfect sense. Thanks! I knew I can always count on a fellow MSTie.
:)
The other problem I have continuously is, when I'm working with dictionaries, figuring out 'how do I get the 'name' half of this object in a dict?' And this function is a great reminder of how to do that. If you called the item in a loop iterating over the items in the dict, there's already a variable that automatically represents the name of the item. In this loop, letter represents the NAME of the item, not 'the item'. That is, letter is a string, not a dictionary entry.
Join our real-time social learning platform and learn together with your friends!