Analyze a sentence: count its words, its unique words, and how often one word appears.
How it works
Splitting into words
.split() with no argument breaks a string at the spaces and gives you a list of words. len() of that list is the word count.
line = "a bb a ccc"
words = line.split()
print(words)
print(len(words))
['a', 'bb', 'a', 'ccc']
4
Unique items with set()
set() keeps one copy of each item and drops the duplicates, so len(set(...)) counts the different items:
colors = ["red", "blue", "red"]
print(len(colors))
print(len(set(colors)))
Counting matches in a function
def count_big(nums, limit):
count = 0
for n in nums:
if n > limit:
count = count + 1
return count
print(count_big([5, 12, 30], 10))
Gotcha: len() of the string counts characters
len() on the sentence itself counts every letter and space, not the words. Split first:
s = "hi there"
print(len(s))
print(len(s.split()))
Your task
The starter code gives you sentence, plus placeholder values to replace.
- Use
.split() to break sentence into a list, stored in words. - Use
len() to count the words, stored in word_count. - Write
count_word(word_list, target) with a for loop inside. It returns how many items in word_list equal target, and 0 if there are none. - Call
count_word(words, "the") and store the result in the_count. - Print three lines with f-strings:
Words: <word_count>, Unique: <number of unique words> using len(set(words)), and 'the' appears <the_count> times.
The checker also calls count_word on other lists, so don't type the counts in.
Expected output
Words: 11
Unique: 9
'the' appears 3 times
Hint
count_word follows the same pattern as count_big, but the if compares each word with target using ==.