计算字符串中元音或辅音的总数



问题:写一个函数letter_count(),它将接受字符串列表或元组和字符串状态,并返回满足字符串状态的字母数

def lettercount(strings, state) :
if type(strings) != list and type(strings) != tuple :
raise TypeError("First input is not a list or a tuple")
if type(state) != str :
raise TypeError("String state strmust be a string!")
if state != "vowels" and state != "consonants" :
raise ValueError("String state str may only be ‘vowels’ or ‘consonants’.")
vowels = "aeiou"
letters = ""
if len(strings) == 0 :
return 0
i = 0
while i < len(strings) :
if type(strings[i]) != str :
raise InterruptedError("{} is not a string!".format(strings[i]))
letters += strings[i]
i += 1
counter = 0
i = 0
while i < len(letters) :
j = 0
while j < len(vowels) :
if type(state) == "vowels" :
if letters[i].lower() == vowels[j] :
counter += 1
if type(state) == "consonants" :
counter= i+1
j += 1
i += 1
return counter
print(letter_count(['hello','my','name','is','V@#$'], 'vowels')) #5
print(letter_count(['asdf'], 'consonants')) #3
print(letter_count([], 'vowels')) #0
print(letter_count(['qwe#$%'], 'consonants')) #2

我不明白为什么辅音不能计算。请帮帮我。

这样的检查总是返回false

if type(state) == "vowels" :

if type(state) == "consonants" :

将返回str,你只需要像这样检查

if state == "vowels" :

if state == "consonants" :

我已经修改了您的代码,以返回您期望的结果

def letter_count(strings, state):
if type(strings) != list and type(strings) != tuple :
raise TypeError("First input is not a list or a tuple")
if type(state) != str :
raise TypeError("String state strmust be a string!")
if state != "vowels" and state != "consonants" :
raise ValueError("String state str may only be vowels or consonants.")
vowels = "aeiou"
letters = ""
if len(strings) == 0 :
return 0
i = 0
while i < len(strings) :
if type(strings[i]) != str :
raise InterruptedError("{} is not a string!".format(strings[i]))
letters += strings[i]
i += 1
counter = 0
i = 0
while i < len(letters) :
if state == "vowels" :
if letters[i].lower() in vowels:
counter += 1
if state == "consonants" :
if letters[i].lower() not in vowels and letters[i].isalnum():
counter += 1
i += 1
return counter
print(letter_count(['hello','my','name','is','V@#$'], 'vowels')) #5
print(letter_count(['asdf'], 'consonants')) #3
print(letter_count([], 'vowels')) #0
print(letter_count(['qwe#$%'], 'consonants')) #2

输出
5
3
0
2
j = 0
while j < len(vowels) :
if type(state) == "vowels" :
if letters[i].lower() == vowels[j] :

应该

if letters[i].lower() in vowels:

最新更新