runtime
112 / 500
question 112 Collection Algorithms · hard

Top sellers in each category

Merchandising wants the best sellers per category for the home page. Given one row per product with its units sold, return the names of the top n products in each category, best first.

Functiontop_products(rows, n)
rowsdictionaries with category, product and units (a whole number)
nhow many products to return per category, at least 1
Returns{category: [product names]} with at most n names per category, most units first; {} for no rows
Tiesproducts with the same units keep the order of the rows (the earlier row ranks higher)
Examples
calltop_products([{'category': 'sports', 'product': 'Ultra Bike Light', 'units': 14}, {'category': 'home', 'product': 'Deluxe Vase', 'units': 9}, {'category': 'sports', 'product': 'Travel Yoga Mat', 'units': 21}, {'category': 'electronics', 'product': 'Organic Speaker', 'units': 6}, {'category': 'sports', 'product': 'Studio Tent', 'units': 14}, {'category': 'home', 'product': 'Nordic Candle', 'units': 12}], 2)returns{'sports': ['Travel Yoga Mat', 'Ultra Bike Light'], 'home': ['Nordic Candle', 'Deluxe Vase'], 'electronics': ['Organic Speaker']}
calltop_products([{'category': 'sports', 'product': 'Ultra Bike Light', 'units': 14}, {'category': 'home', 'product': 'Deluxe Vase', 'units': 9}, {'category': 'sports', 'product': 'Travel Yoga Mat', 'units': 21}, {'category': 'electronics', 'product': 'Organic Speaker', 'units': 6}, {'category': 'sports', 'product': 'Studio Tent', 'units': 14}, {'category': 'home', 'product': 'Nordic Candle', 'units': 12}], 1)returns{'sports': ['Travel Yoga Mat'], 'home': ['Nordic Candle'], 'electronics': ['Organic Speaker']}
calltop_products([], 3)returns{}

Loading your progress…

Top sellers in each category — Python practice · Runtime