Drill

ProblemsPython › reporting

The best selling products this week

mediumreportingPython

The weekly email lists the top products by units sold. Sales come in one row per transaction, so the same product appears many times.

top_sellers(sales: list<Sale>, how_many: int) → list<string>

Solve it in the editor →

Where you start

def top_sellers(sales: list[Sale], how_many: int) -> list[str]:
    

Worked examples

CallResult
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]

The same problem in another language

More reporting problems in Python