Top k most frequent
Find the k values that appear most often in a list. Count each value
with a dictionary, then rank the (value, count) pairs: highest count
first, and when counts tie, the smaller value first. sorted or
heapq.nsmallest can do the ranking if you give them a key that returns
(-count, value); the minus sign makes bigger counts come first.
Write most_frequent(items, k) that returns the k most frequent values
as a list, most frequent first. Ties are broken by the value itself in
ascending order. k never exceeds the number of distinct values.
most_frequent(["a", "b", "a", "c", "b", "a"], 2) -> ["a", "b"]
most_frequent([3, 1, 3, 1, 2], 2) -> [1, 3]
import heapq
def most_frequent(items, k):
...