是否有更有效的方法来计算字符串中的元音数量?

时间:2017-11-14 04:26:02

标签: python

def processStrings(userPhrase):
    """ This function will accept the phrase as string and will count every 
        instance of vowel then return a dictionary with key:values of each 
        vowel and amount of occurrences in string.
    """

    vowelCount = {i:userPhrase.count(i) for i in 'AEIOU'}

    return (vowelCount)

我是StackOverflow和Programming的新手。我把这个函数写成了课程的小程序的一部分,我现在很想知道最有效的解决方案是什么。我们被告知在开发高效解决方案时展示了对适用概念的深刻理解,据我所知,这必须非常接近,因为它使用字典并且count()应该是好的。我想知道我是否遗漏了一些事情,因为它必须迭代整个短语5次以获得值,但我无法弄清楚是否有更好的解决方案,这将意味着更少的处理时间或内存使用量,如果我使用更大字符串的功能,搜索的不仅仅是元音或其他东西。

1 个答案:

答案 0 :(得分:2)

使用Counter,然后提取元音的值并重新调整它们可能会更有效:

from collections import Counter

def count_vowels(phrase):
    """ accepts a string and counts the number of each vowels.
    returns a dictionary key --> values 
            of each vowel and their number of occurrences.
    """
    vowels = "aeiou"
    frequencies = Counter(phrase.lower())
    return {vowel: frequencies[vowel] for vowel in vowels}    

作为单行:

(正如@stevenRumbalski在评论中所建议的那样)

from collections import Counter

def count_vowels(phrase):
    """ accepts a string and counts the number of each vowels.
    returns a dictionary key --> values 
            of each vowel and their number of occurrences.
    """
    vowels = "aeiou"
    return Counter(c for c in phrase.lower() if c in vowels)