
Code
Count the Loot
Dictionaries are brilliant for counting. Use each thing as a key and its count as the value:
counts = {}
for word in ["hi", "yo", "hi"]:
counts[word] = counts.get(word, 0) + 1
print(counts) # {'hi': 2, 'yo': 1}
The trick is counts.get(word, 0). The first time we see a word,
it isn't in the dict yet. So .get gives 0, and we store 0 + 1.
Pip tip: Later you'll meet
collections.Counter, which does this in one line. Now you'll know how it works inside!
Assignment
- Fill
countsso each loot item maps to how many times it appears. - Then find
most_common: the item with the highest count. Loop overcounts.items()and keep the best one, just like finding the heaviest crate.
- Fill
countsso each loot item maps to how many times it appears. - Then find
most_common: the item with the highest count. Loop overcounts.items()and keep the best one, just like finding the heaviest crate.
main.py Python sleeping
Press Run to try your code, then Check to test it.