python - count items using nested loops -
def count_vowel_phonemes(phonemes): """ (list of list of str) -> int return number of vowel phonemes in phonemes. >>> phonemes = [['n', 'ow1'], ['y', 'eh1', 's']] >>> count_vowel_phonemes(phonemes) 2 """ number_of_vowel_phonemes = 0 phoneme in phonemes: item in phoneme: if 0 or 1 or 2 in item: number_of_vowel_phonemes = number_of_vowel_phonemes + 1 return number_of_vowel_phonemes
description: vowel phoneme phoneme last character 0, 1, or 2. examples, word before (b ih0 f ao1 r) contains 2 vowel phonemes , word gap (g ae1 p) has one.
the parameter represents list of list of phonemes. function return number of vowel phonemes found in list of list of phonemes. question asks me count number of digits in list, codes keep returning 0 strange. there wrong code? in advance!!
if any(i in item in ("0", "1","2"):
your code return 5
test input or 1
evaluate true
, checking bool(1)
not checking if 1
in item
, comparing ints
strings
.
you reduce code generator expression sum
, using str.endswith
find subelements ending in 0,1 or 2:
return sum(item.endswith(("0","1","2")) phoneme in phonemes item in phoneme)
which outputs:
in [4]: phonemes = [['n', 'ow1'], ['y', 'eh1', 's']] in [5]: count_vowel_phonemes(phonemes) out[5]: 2
the correct method test using or
be:
if "0" in item or "1" in item or "2" in item:
which equivalent any
line.
Comments
Post a Comment