The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
Use a dictionary to count the number of times each word occurs.
Optionally, convert all words to lowercase for case-insensitive calculations.
Solution in Python
def count_word_frequency(sentence):
# Step 1: Convert to lowercase to avoid case mismatches
sentence = sentence.lower()
# Step 2: Split sentence into words
words = sentence.split()
# Step 3: Create an empty dictionary to hold word counts
word_count = {}
# Step 4: Count each word
for word in words:
if word in word_count:
word_count[word] += 1 # Increment count if word already exists
else:
word_count[word] = 1 # Initialize count if word appears for the first time
return word_count
# Example usage:
sentence = "Hello world hello"
result = count_word_frequency(sentence)
print(result)
Explanation
sentence.lower(): Ensures "Hello" and "hello" are treated as the same.
sentence.split(): Splits on whitespace by default.
The dictionary word_count stores each word as a key and its count as a value.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Problem Statement
Given a sentence like:
You need to return:
Approach
Solution in Python
Explanation
sentence.lower(): Ensures "Hello" and "hello" are treated as the same.sentence.split(): Splits on whitespace by default.word_countstores each word as a key and its count as a value.Output: