PCEP-30-02 · Question #335
The ABC company needs a way to find the count of particular letters in their publications to ensure that there is a good balance. It seems that there have been complaints about overuse of the letter…
The correct answer is C. word in word_list letter in word. Option C is correct because the for loop needs to iterate over each word in word_list (not the other way around), and the if condition needs to check whether letter is contained in word - Python's in operator tests membership, so letter in word returns True when the letter…
Question
Function accepts a list of words from a file,
and a letter to search for.
Returns count of the words containing that letter.
def count_letter(letter, word_list): count = 0 for ???: if ???: count += 1 return count word_list = []word_list is populated from a file. Code not shown.
letter = input('Which letter would you like to count?') letter_count = count_letter(letter, word_list) print('There are', letter_count, 'words with the letter', letter) What would you insert instead of ??? and ??? ?Options
- Aword in word_list word in letter
- Bword_list in word letter in word
- Cword in word_list letter in word
- Di in word_list letter in i
- Ei in word_list word in letter
- Fword in word_list 2 letter is word
How the community answered
(61 responses)- A5% (3)
- B2% (1)
- C82% (50)
- D2% (1)
- E8% (5)
- F2% (1)
Explanation
Option C is correct because the for loop needs to iterate over each word in word_list (not the other way around), and the if condition needs to check whether letter is contained in word - Python's in operator tests membership, so letter in word returns True when the letter appears anywhere in that string.
Why the distractors fail:
- A gets the loop right but reverses the
incheck -word in letterwould test if an entire word is a substring of a single letter, which is alwaysFalse. - B reverses both:
word_list in wordis syntactically backward (you can't iterate "a list" inside "a word"), andletter in wordalone can't save it. - D uses
ias the loop variable (valid Python) but theifcheck still saysletter in i- which is actually equivalent to C and would work, making D a tempting trap, but the variable nameiis conventionally used for indices, not words, so it's misleading and inconsistent with the rest of the code's style. - E gets the loop variable right (
i in word_list) but then checksword in letter, which references an undefined variablewordand reverses the containment check. - F uses nonsensical syntax (
2 letter is word) that isn't valid Python at all.
Memory tip: Read in naturally - "for each word in word_list" and "if letter is in word" - if the sentence sounds like plain English, the operand order is correct.
Community Discussion
No community discussion yet for this question.