Returns the `k_value` most frequently occurring words, in non-increasing order of occurrence. In this context, a word is defined as an element in the provided list. In case `k_value` is greater than the number of distinct words, a value of k equal to the number of distinct word
(words: list[str], k_value: int)
| 65 | |
| 66 | |
| 67 | def top_k_frequent_words(words: list[str], k_value: int) -> list[str]: |
| 68 | """ |
| 69 | Returns the `k_value` most frequently occurring words, |
| 70 | in non-increasing order of occurrence. |
| 71 | In this context, a word is defined as an element in the provided list. |
| 72 | |
| 73 | In case `k_value` is greater than the number of distinct words, a value of k equal |
| 74 | to the number of distinct words will be considered, instead. |
| 75 | |
| 76 | >>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 3) |
| 77 | ['c', 'a', 'b'] |
| 78 | >>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 2) |
| 79 | ['c', 'a'] |
| 80 | >>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 1) |
| 81 | ['c'] |
| 82 | >>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 0) |
| 83 | [] |
| 84 | >>> top_k_frequent_words([], 1) |
| 85 | [] |
| 86 | >>> top_k_frequent_words(['a', 'a'], 2) |
| 87 | ['a'] |
| 88 | """ |
| 89 | heap: Heap[WordCount] = Heap() |
| 90 | count_by_word = Counter(words) |
| 91 | heap.build_max_heap( |
| 92 | [WordCount(word, count) for word, count in count_by_word.items()] |
| 93 | ) |
| 94 | return [heap.extract_max().word for _ in range(min(k_value, len(count_by_word)))] |
| 95 | |
| 96 | |
| 97 | if __name__ == "__main__": |
nothing calls this directly
no test coverage detected