Top Bars Plus Other

Data with PythonMedium+10 XP+10

Top Bars Plus Other

A bar chart with forty thin bars is unreadable. The usual fix is to keep the most common categories and lump the rest into one bar called "Other".

Task: write top_bars(items, k). items is a list of category names, one per sale.

Return a list of [name, count] pairs:

  • the k categories with the highest counts, biggest first
  • if two categories have the same count, the one that comes first alphabetically goes first
  • then, only if any categories are left over, one final pair ["Other", total], where total is the number of sales in all the left-over categories

If there are k categories or fewer, there's no "Other" bar. No category is called "Other", and k is at least 1.

Examples

items = ["tea", "coffee", "tea", "juice", "coffee", "tea", "water"]
k = 2
returns [['tea', 3], ['coffee', 2], ['Other', 2]]
items = ["red", "blue", "red"]
k = 5
returns [['red', 2], ['blue', 1]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run