我正在尝试创建一个函数来评估是否连续至少包含三个元音。
到目前为止,我已经尝试过: (我不知道如何评估它们是否连续) 有什么想法吗?
def isConsecutive(word):
# initialize vowel count
vCounter = 0
for letter in word:
if letter == isVowel(word):
vCounter += 1
else:
vCounter = 0
if vCounter < 3:
return False
return True
def isVowel(char):
return len(char) == 1 and char.lower() in 'aeiou'
答案 0 :(得分:2)
检查是否按顺序到达第三步,应该在vCounter += 1
之后。如果有三个点,则返回true。
此外,isVowel
检查应应用于letter
,而不是整个word
。
def isVowel(char):
return char.lower() in 'aeiou'
def isConsecutive(word):
# initialize vowel count
vCounter = 0
for letter in word:
if isVowel(letter): # <= check if the letter is a vowel
vCounter += 1
if vCounter >= 3: # <= do the check right here
return True
else:
vCounter = 0
return False # <= if we did not find three vovels in the loop, then there is none
print "hello: " + str(isConsecutive("hello"))
print "heeello: " + str(isConsecutive("heeello"))
print "hellooo: " + str(isConsecutive("hellooo"))
在线试用: DEMO
答案 1 :(得分:0)
您还可以通过两个列表理解来做到这一点:
。
def three_consecutive_vowels(s):
is_vow = [c.lower() in 'aeiou' for c in s]
three_cons = [all(is_vow[i:i+2]) for i in range(len(is_vow) - 2)]
return any(three_cons)
测试:
words = ['hellO', 'heIah', 'aAarrgh']
for w in words:
print(three_consecutive_vowels(w))
False
True
True