MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / top_k_frequent_words

Function top_k_frequent_words

strings/top_k_frequent_words.py:67–94  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

65
66
67def 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
97if __name__ == "__main__":

Callers

nothing calls this directly

Calls 4

build_max_heapMethod · 0.95
extract_maxMethod · 0.95
HeapClass · 0.90
WordCountClass · 0.85

Tested by

no test coverage detected