Editor

Best Sellers From the Till

#580 · Modules and random · Intermediate · 60 XP · about 10 min

A cafe's till records each sale as a Sale named tuple with the fields item and qty, so sale.item and sale.qty read them by name. Sale is provided.

Write best_sellers(sales, k) that adds up how many of each item were sold and returns the k best sellers as a list of (item, total) tuples, the biggest total first. Items with the same total keep the order in which they first appear in sales. If fewer than k different items were sold, return them all.

collections.Counter does most of this work: it adds up counts by key, and its most_common(k) method keeps ties in the order the keys were first added.

Examples

sales = [Sale('tea', 2), Sale('cake', 1), Sale('tea', 1), Sale('bun', 3)]
best_sellers(sales, 2)  # returns [('tea', 3), ('bun', 3)]
best_sellers(sales, 5)  # returns [('tea', 3), ('bun', 3), ('cake', 1)]

Tea and buns both sold 3, and tea was sold first, so it comes first.

Constraints

  • 0 <= k <= 100
  • At most 100,000 sales, each with a qty of at least 1.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.