Problem 336681 · medium · Level 03 Linear Management & Searching

Customers Who Bought This Also Bought

py-counter · defaultdict · Counter · pairs

A grocery shop wants to show, next to every product, the product most often bought with it. You get the shop's baskets: each basket is a list of item names, and an item scanned twice appears twice.

Write bought_together(baskets) that returns a dictionary from each item to a pair (partner, count): partner is the other item that shares the most baskets with it, and count is the number of baskets they share. An item counts only once per basket, however often it was scanned. If several partners tie, choose the alphabetically first. An item that never shares a basket with a different item is left out.

The helper grocery_baskets(n, seed) generates n baskets; try it with Run.

Examples

Input:  baskets = [["tea", "milk", "tea"], ["milk", "bread"], ["tea", "milk"], ["jam"]]
Output: {"tea": ("milk", 2), "milk": ("tea", 2), "bread": ("milk", 1)}
Explanation: tea and milk share two baskets. jam never shares a basket, so it is left out.

Input:  baskets = [["b", "a", "c"]]
Output: {"a": ("b", 1), "b": ("a", 1), "c": ("a", 1)}

Constraints

  • Up to 3 * 10**4 baskets with at most 10 items each.

Goals

  • Group counts by a key with `defaultdict(Counter)`
  • Count each pair of different items once per basket
  • Pick the best entry of a `Counter` with a tie-break
Starting Python…