The best selling products this week
The weekly email lists the top products by units sold. Sales come in one row per transaction, so the same product appears many times.
- Add up the units per product name first.
- Order by units sold, largest first; products level on units go alphabetically.
- Return at most `howMany` names, or fewer if there are not that many products.
- Asking for zero or fewer returns nothing.
top_sellers(sales: list<Sale>, how_many: int) → list<string>
Where you start
def top_sellers(sales: list[Sale], how_many: int) -> list[str]:
Worked examples
| Call | Result |
|---|---|
top_sellers([Sale(name="mug", qty=5), Sale(name="pen", qty=3), Sale(name="mug", qty=2)], 2) | ["mug", "pen"] |
top_sellers([Sale(name="zip", qty=1), Sale(name="ace", qty=1)], 2) | ["ace", "zip"] |
top_sellers([Sale(name="mug", qty=5), Sale(name="pen", qty=9)], 1) | ["pen"] |
top_sellers([Sale(name="mug", qty=5)], 0) | [] |
Hint
Aggregate into a map, then sort the entries. The tie-break is what most solutions forget.
Reference solution in Python
def top_sellers(sales: list[Sale], how_many: int) -> list[str]:
totals = {}
for s in sales:
totals[s.name] = totals.get(s.name, 0) + s.qty
names = sorted(totals, key=lambda n: (-totals[n], n))
return [] if how_many <= 0 else names[:how_many]