Write Python logic to count word frequency in a string.
1
Times asked
Jul 2026
Last seen
Jul 2026
First seen
💡 Model Answer
You can solve this by splitting the string into words and using a dictionary or collections.Counter to tally occurrences. For example:
python
from collections import Counter
def word_frequency(text):
# Normalize: lower case and split on whitespace
words = text.lower().split()
return Counter(words)
text = "Hello world hello"
print(word_frequency(text)) # Counter({'hello': 2, 'world': 1})
This runs in O(n) time where n is the number of words, and uses O(k) space for k unique words. If you need to handle punctuation, use regex or str.translate to strip punctuation before splitting.
Sign in to unlock the rest of this answer
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