Top-K Items via collections.Counter

Easy ⏱ 8 min 87% acceptance ★★★★★ 4.5
Write top_k(items, k) returning the k most common elements as a list of (item, count) tuples using collections.Counter.most_common — the standard library beats hand-rolled tallying.

Examples

Example 1
Input
top_k(['a', 'b', 'a', 'c', 'a', 'b'], 2)
Output
[('a', 3), ('b', 2)]
Explanation

a appears 3 times, b twice.

Constraints

  • Use collections.Counter.
  • Return exactly min(k, distinct) tuples.

Topics

Modules & Packagescollections

Companies

AmazonGoogleNetflix

Hints

Hint 1

from collections import Counter.

Hint 2

Counter(items).most_common(k) is the whole job.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.