Python: Get the k most frequent elements from a given non-empty list of words using Heap queue algorithm
Python heap queue algorithm: Exercise-14 with Solution
Write a Python program to get the k most frequent elements from a given non-empty list of words using the heap queue algorithm
Range of k, 1 ≤ k ≤ number of unique elements and input words contain only lowercase letters.
import heapq from collections import Counter class Solution: def top_K_Frequent(self, words, k): """ :type words: List[str] :type k: int :return type: List[str] """ ctr = Counter(words) heap = [(-ctr[word], word) for word in ctr] heapq.heapify(heap) return [heapq.heappop(heap) for _ in range(k)] if __name__ == '__main__': words = ["a", "abc", "abcdef", "a", "abcd", "abcd", "abc", "abcdefg"] k = 3 s = Solution() print("3 most frequent elements:") print(s.top_K_Frequent(words, k))
3 most frequent elements: ['a', 'abc', 'abcd']
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to find the nth super ugly number from a given prime list of size k using Heap queue algorithm.
Next: Write a Python program to check if the letters of a given string can be rearranged so that two characters that are adjacent to each other are different using Heap queue algorithm.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join