Counter({'apple': 3, 'banana': 2, 'orange': 1}) -> Option C
Quick Check:
Count matches word occurrences [OK]
Hint: Count words carefully; Counter shows counts with 'Counter()' [OK]
Common Mistakes:
Ignoring Counter output format
Miscounting word frequencies
Confusing dictionary and Counter print styles
4.
Find the error in this code that tries to count words:
from collections import Counter
text = "Hello world! Hello"
words = text.split()
count = Counter(words.lower())
print(count)
medium
A. Cannot call lower() on a list; should call on each word
B. Missing import statement for Counter
C. split() should be split(' ')
D. Counter cannot count strings
Solution
Step 1: Identify the type of 'words'
words is a list of strings after split().
Step 2: Check the use of lower()
Calling words.lower() is invalid because lists have no lower() method; lower() applies to strings.
Final Answer:
Cannot call lower() on a list; should call on each word -> Option A
Quick Check:
lower() works on strings, not lists [OK]
Hint: Apply lower() to each word, not the whole list [OK]
Common Mistakes:
Calling lower() on list instead of string
Ignoring error messages
Thinking split() needs arguments
5.
You want to count words ignoring case and punctuation in this text:
text = "Hello, hello! How are you? Are you fine?"
Which code correctly cleans and counts words?
hard
A. import re
from collections import Counter
words = re.findall(r'\w+', text)
count = Counter(words)
print(count)
B. import string
from collections import Counter
clean_text = text.lower().translate(str.maketrans('', '', string.punctuation))
words = clean_text.split()
count = Counter(words)
print(count)
C. from collections import Counter
words = text.split()
count = Counter(words)
print(count)
D. from collections import Counter
words = text.lower().split()
count = Counter(words)
print(count)
Solution
Step 1: Understand the need to remove punctuation and lowercase
To count words ignoring case and punctuation, text must be lowercased and punctuation removed.
Step 2: Check each option's approach
import string
from collections import Counter
clean_text = text.lower().translate(str.maketrans('', '', string.punctuation))
words = clean_text.split()
count = Counter(words)
print(count) uses string.punctuation with translate() to remove punctuation and lowercases text before splitting, which is correct.
Final Answer:
Code that lowercases and removes punctuation before counting -> Option B
Quick Check:
Clean text + Counter = accurate word frequency [OK]
Hint: Remove punctuation and lowercase before splitting words [OK]
Common Mistakes:
Not removing punctuation
Counting words with mixed cases separately
Using split() without cleaning text
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.