该函数正好包含5个元音中的每一个

时间:2018-10-16 02:31:22

标签: python python-2.7

我正在尝试创建一个函数来评估是否准确包含5个元音中的每个元音。

到目前为止,我已经尝试过:(我不知道现在如何只限制每个元音之一)

def isVowel(char): #=> Helper function
    return len(char) == 1 and char.lower() in 'aeiou'

def fiveVowelsOneOfEach(word):
    oneVowelOfEachCounter = 0
    for char in word:
        if isVowel(char):
            if char == 'a':
                oneVowelOfEachCounter += 1
            if char == 'e':
                oneVowelOfEachCounter += 1
            if char == 'i':
                oneVowelOfEachCounter += 1
            if char == 'o':
                oneVowelOfEachCounter += 1
            if char == 'u':
                oneVowelOfEachCounter += 1
            if oneVowelOfEachCounter == 5: 
                return True

4 个答案:

答案 0 :(得分:4)

只需:

s = 'aeiou'
s2 = 'aaeiou'
def checker(s):
    return all(s.lower().count(i)==1 for i in 'aeiou')
print(checker(s))
print(checker(s2))

输出:

True
False

这一切都需要,检查每个元音的计数是否为一个

答案 1 :(得分:1)

一种更简单的方法

goodstr = 'aeiou'
badstr = 'aaeiou'
vowels = ['a','e','i','o','u'] # or a string "aeiou"

def fiveVowelsIsOneOfEach(word):
    for vowel in vowels:
        if word.count(vowel) != 1:
            return False
    return True


print(fiveVowelsIsOneOfEach(goodstr))   # returns True
print(fiveVowelsIsOneOfEach(badstr))    # returns False

答案 2 :(得分:0)

更新了答案,以解决问题中的问题。还添加了不使用计数器的版本。

from collections import Counter

word = 'aaeiuo'
vowels = 'aeiuo'
c = Counter(word)
vowel_count = sum([1 if c[vowel] > 0 else 0 for vowel in vowels])
print(vowel_count) # 5
#without using counter
vowel_count = sum([1 if word.count(vowel) > 0 else 0 for vowel in vowels])
print(vowel_count) # 5

答案 3 :(得分:0)

def fiveVowelsOneOfEach(word):
    oneVowelOfEachCounter = 0
    vowels = list('aeiou')
    dummy_vowels = list(chars)
    for char in word:
        if char in vowels:
            vowels.remove(char)
            continue
        elif char in dummy_vowels:
            return False
    if len(vowels) == 0:
        return True
    return False

这应该有效。诀窍是使用一个列表和一个虚拟列表,以确保每个元音仅被计数一次。