How can I use collections.Counter and counts.most_common(k) to get the top k words from a string?
💡 Model Answer
collections.Counter is a specialized dictionary that automatically counts hashable objects. To find the top k words in a string, you first split the string into words, then pass that list to Counter. The Counter object builds a frequency map in linear time, O(n), where n is the number of words. The most_common(k) method then returns a list of the k most frequent items as (word, count) tuples, sorted by count in descending order. Internally, most_common uses a heap to keep track of the top k elements, giving a time complexity of O(n + k log n). If k is larger than the number of unique words, most_common returns all items. This approach is concise, leverages built‑in Python utilities, and is ideal for quick text analytics tasks. Example: text = 'apple orange banana apple apple orange grape banana grape'; words = text.split(); counts = Counter(words); top5 = counts.most_common(5). This method is often used in log analysis, search indexing, and natural language processing.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500