Find the top 5 most common words in the given text using list comprehension.
💡 Model Answer
The solution is identical to the previous one: text = 'apple orange banana apple apple orange grape banana grape'; words = text.split(); counts = {w: [w for w in words].count(w) for w in set(words)}; top5 = sorted(counts.items(), key=lambda x: x[1], reverse=True)[:5] The code uses a list comprehension to count each unique word, sorts the dictionary by count, and slices the first five entries. Complexity is O(n^2) for the count operation, but it is acceptable for short strings. This demonstrates the ability to use Python's concise syntax to perform a common data‑analysis task. The sorted function ensures the results are ordered by frequency, and the slice [:5] returns the top five words. This pattern is a quick way to demonstrate familiarity with Python's functional features. This approach is simple yet effective for small datasets and showcases your ability to write concise, readable code using Python's expressive features. If performance becomes a concern, you could replace the list comprehension with a Counter or a heap‑based approach to reduce time complexity.
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