Richard Bruno
Richard Bruno

Reputation: 123

Why do I get different results iterating over dictionary

I have two functions that iterate over a dictionary for a scrabble type game. I don't understand why one doesn't work and while the other does using the test input. I have used pythontutor.com to try and find out why one of them doesn't get the correct output. This function gives the correct output

def updateHand(hand, word):
    
    newhand = hand.copy()
    for letter in word:
        if letter in newhand.keys():
            newhand[letter] -= 1        
    return newhand
print(updateHand({'h': 1, 'e': 1, 'l': 2, 'o': 1}, 'hello'))
print(updateHand({'a': 1, 'q': 1, 'l': 2, 'm': 1, 'u': 1, 'i': 1},'quail'))

correct output:

{'h': 0, 'e': 0, 'l': 0, 'o': 0} 

and

{'a': 0, 'q': 0, 'l': 1, 'm': 1, 'u': 0, 'i': 0}

This function doesn't give correct output and I would like to know why:

def updateHand(hand, word):
    
    newhand = hand.copy()
    for letter in word:
       newhand[letter] = hand.get(letter, 0) - 1        
    return newhand

This is the output for this function the 'l' value should be zero.

{'h': 0, 'e': 0, 'l': 1, 'o': 0}

Upvotes: 0

Views: 79

Answers (1)

heLomaN
heLomaN

Reputation: 1794

The reason is the count of l in hand is not updated in the second solution.

Try this:

def updateHand(hand, word):
    
    newhand = hand.copy()
    for letter in word:
       # use newhand here
       newhand[letter] = newhand.get(letter, 0) - 1        
    return newhand

In you code, just track the status of newhand and hand when encountering l:

after first l: newhand = {'h': 0, 'e': 0, 'l': 1, 'o': 1} , hand = {'h': 1, 'e': 1, 'l': 2, 'o': 1}

after second l: since hand = {'h': 1, 'e': 1, 'l': 2, 'o': 1} , so newhand = {'h': 0, 'e': 0, 'l': 1, 'o': 1} .

The key deference is that the count in newhand is override by data modified based on hand.

Upvotes: 4

Related Questions