Write code to find the top 5 most common words in the given text using list comprehension.
💡 Model Answer
You can use a list comprehension to build a dictionary of word counts and then sort it. One concise pattern is: 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] This code splits the string, creates a set of unique words, and for each word uses the list comprehension to count its occurrences. The resulting dictionary is then sorted by value in descending order, and the first five items are taken. Complexity is O(n^2) because count() scans the list for each unique word, but for small inputs it is acceptable. A more efficient approach would use Counter, but the question explicitly asks for list comprehension. The code demonstrates how to combine list comprehensions with built‑in functions to solve a common text‑analysis task. The set comprehension ensures we only iterate over unique words, reducing the number of count operations. The sorted function uses Timsort, giving O(m log m) where m is the number of unique words. The final slice returns the top 5.
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