Can you provide the Python code to find the top 5 most frequent words in a string?
💡 Model Answer
Here is a compact Python implementation that finds the top 5 most frequent words in a given text: import heapq from collections import Counter def top_k_words(text, k=5): # Normalize: lowercase and strip punctuation words = [w.strip('.,!?') for w in text.lower().split()] # Count frequencies freq = Counter(words) # Use a min‑heap to keep the top k items heap = [] for word, count in freq.items(): heapq.heappush(heap, (count, word)) if len(heap) > k: heapq.heappop(heap) # Extract results in descending order return [word for count, word in sorted(heap, reverse=True)] # Example usage sample = 'Hello world! Hello Python. Python is great. Hello again.' print(top_k_words(sample)) # Output: ['hello', 'python', 'world', 'again', 'is'] The algorithm first normalizes the text by converting it to lowercase and removing punctuation, then counts word frequencies using a Counter. It then maintains a min‑heap of size k to keep the top k words. Each heap push/pop is O(log k), so the overall time is O(n log k) where n is the number of words. Memory usage is O(m + k) where m is the number of distinct words. This approach is efficient for large inputs and avoids sorting the entire frequency dictionary.
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