繁体   English   中英

计算字符串中唯一元音的数量

[英]Counting the number of unique vowels in a string

我有以下任务:

导入sys模块并创建一个带有字符串参数的 function,该字符串参数将打印字符串中唯一元音的数量,无论它是大写还是小写。

例如:

Test 1: The argument swEet should print 1
Test 2: The argument “Aaa aeeE” should print 2
Test 3: The argument "eiOuayOI j_#Ra" should print 5

我有以下代码:

import sys

def count_vowels(args):
    vowels = set()

    for arg in args:
        for char in arg:
            if char.lower() in 'aeiou':
                vowels.add(char)
    return len(vowels)

print(count_vowels(sys.argv[1:]))

测试用例 1 是唯一打印出预期 output 的测试。其他两个测试用例,测试 2 和测试 3,没有打印出正确的预期结果。 测试 2 打印 5 而不是预期的 output 的 4,测试 3 打印 6 而不是预期的 output 的 5。

我认为你把事情复杂化了。 要获得唯一元音的数量,您可以将整个字符串小写,然后对小写字符串调用set()以获得一组唯一字母。 然后您可以检查每个元音是否在此集合中。 如果是,它会出现在文本中,否则不会:

def count_vowels(text):
    letters = set(text.lower())
    
    count = 0
    for vowel in 'aeiou':
        if vowel in letters:
            count += 1
    return count

print(count_vowels("Aaa aeeE")) # Prints 2
print(count_vowels("eiOuayOI j_#Ra")) # Prints 5

如果您更喜欢单线,您可以这样做:

def count_vowels(text):
    return sum(1 for vowel in 'aeiou' if vowel in set(text.lower()))

或这个(如psmears所建议的):

def count_vowels(text):
    return len(set(text.lower()) & set('aeiou'))

您仍在混合上/下套管,请参阅其他答案。

这个有很多更短的版本

def count_vowels(word):
    # all letters you are interested in 
    allowed = frozenset("aeiou")
    # get the len of the intersection between allowed and lower cased word
    return len(allowed.intersection( word.lower()))

tests = [("swEet",1), ("Aaa aeeE", 2),("eiOuayOI j_#Ra", 5)]

for t in tests:
    print(t[0], "is", count_vowels(t[0]), "should be", t[1])

Output:

swEet is 1 should be 1
Aaa aeeE is 2 should be 2
eiOuayOI j_#Ra is 5 should be 5

这使用(frozen)set.intersection - 并返回它的长度。 frozenset 只是 set 的一个不可变版本。

vowels.add(char)更改为vowels.add(char.lower())

您还应该将char you append 转换为元音set().lower() ,因为现在它按原样添加元音,所以集合可以同时包含oO

vowels.add(char.lower())

其他答案和评论很好地解释了问题,您应该使用变量来计算每个元音的出现次数。 这是一个使用列表理解而不是 for 循环的简短解决方案:

def count_vowels(args: str):
    args = set(args.lower())
    return sum([vowel in args for vowel in 'aeiou'])

您甚至可以将 go 变成 lambda function:

count_vowels = lambda args: sum([vowel in set(args.lower()) for vowel in 'aeiou'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM