
Code
Count & Group
Two tools from collections make aggregation painless.
Counter
A Counter is a dict that counts things:
from collections import Counter
c = Counter(["oil", "wick", "oil", "lens", "oil"])
c["oil"] # 3
c["dragon"] # 0 (missing keys count as 0)
c.most_common(2) # [('oil', 3), ('wick', 1)]
c.update(["wick"]) # add more counts
defaultdict
A defaultdict creates a starting value the first time you touch a
missing key, so you never need if key not in d:.
from collections import defaultdict
fuel = defaultdict(int) # missing -> 0
for isle, litres in [("Ember", 5), ("Frost", 2), ("Ember", 3)]:
fuel[isle] += litres
dict(fuel) # {'Ember': 8, 'Frost': 2}
groups = defaultdict(list) # missing -> []
groups["Ember"].append("Ada")
Assignment
top_items(sales, n):salesis a list of item names. Return thenmost common as a list of(name, count)tuples, most common first.fuel_by_island(records):recordsis a list of(island, litres)tuples. Return a dict of island to total litres.crew_by_role(crew):crewis a list of(name, role)tuples. Return a dict of role to alphabetically sorted list of names.
top_items(sales, n):salesis a list of item names. Return thenmost common as a list of(name, count)tuples, most common first.fuel_by_island(records):recordsis a list of(island, litres)tuples. Return a dict of island to total litres.crew_by_role(crew):crewis a list of(name, role)tuples. Return a dict of role to alphabetically sorted list of names.
main.py Python sleeping
Press Run to try your code, then Check to test it.