Write top_words(words: list[str], k: int) -> list[tuple[str, int]] that returns the k most frequent words as (word, count) pairs, using collections.Counter.
- The most frequent word comes first.
- Words with the same count keep the order of their first appearance in
words. - If there are fewer than
kdifferent words, return all of them.k == 0or an empty list gives[].
top_words(["red", "blue", "red", "green", "blue", "red"], 2) # [("red", 3), ("blue", 2)]
top_words(["b", "a", "a", "b", "c"], 2) # [("b", 2), ("a", 2)] (b appeared first)
top_words(["x"], 5) # [("x", 1)]
0 <= len(words) <= 10^5and0 <= k <= 10^5. Words are compared exactly:"Red"and"red"are different words.- Don't modify
words.
Show hint
Counter(words) counts everything in one pass, and its most_common(k) method already returns the pairs in the order asked for, ties included.