
Code
Tally the Sightings
The collections module has upgraded containers for everyday jobs.
Counter counts things
from collections import Counter
seen = Counter(["gull", "whale", "gull", "otter", "gull"])
print(seen["gull"]) # 3
print(seen["kraken"]) # 0 (no KeyError!)
print(seen.most_common(2)) # [('gull', 3), ('whale', 1)]
defaultdict creates missing values for you
from collections import defaultdict
cargo = defaultdict(list) # missing keys start as []
cargo["Amber Isle"].append("oil")
cargo["Amber Isle"].append("rope")
print(dict(cargo)) # {'Amber Isle': ['oil', 'rope']}
No more if key not in d: d[key] = []. Use defaultdict(int) for
counters starting at 0, or defaultdict(set) for unique groups.
Assignment
top_islands(visits, n):visitsis a list of island names. Return thenmost visited as a list of(island, count)tuples, most visited first.group_by_island(records):recordsis a list of(island, item)tuples. Return adictmapping each island to a list of its items, in their original order.
top_islands(visits, n):visitsis a list of island names. Return thenmost visited as a list of(island, count)tuples, most visited first.group_by_island(records):recordsis a list of(island, item)tuples. Return adictmapping each island to a list of its items, in their original order.
main.py Python sleeping
Press Run to try your code, then Check to test it.