I have a dictionary and a word:
check = {'a': 3, 'e': 1, 'p': 2, 'r': 1, 'u': 1, 't': 1}
word = 'rapturerererer'
I'm looking to run a test if all the letters from word are in check. So I need to keep a running count of all the used up letters and check if there are any negatives at the end.
I have code but it always caps out the values at 0 and never returns the negative values:
for letter in word:
if check.get(letter):
check[letter] -= 1
print(check)
{'a': 2, 'p': 1, 'r': 0, 'e': 0, 't': 0, 'u': 0}
What I'm expecting is this:
{'a': 2, 'p': 1, 'r': -5, 'e': -4, 't': 0, 'u': 0}
Can anyone explain why it's stopping at 0 for these values?
if check.get(letter):
check[letter] -= 1
if check.get(letter) doesn't only fail if letter is missing; it also fails if the value in the dict is "falsy". None is falsy, and so is 0. Once it hits 0 the test fails and no more decrementing happens.
Use in instead.
if letter in check:
check[letter] -= 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With