使用for循环计算总字母数和特定字母的数量\

时间:2018-11-02 19:19:29

标签: python string python-3.x counter

对于一个学校项目,我必须编写一个函数,该函数可以计算字符串中字母的数量,但是也可以计算特定字母的数量,但是,当它是指定字母时,似乎只会增加总字母数。我不明白为什么它没有在3.7中将ascii_lowercase注册为小写字母,除非我彻底误解了一些东西。

def analyze_string(quote, search_letter):
    count_letters = 0
    count_occurance = 0
    phrase = quote.lower()
    letter = string.ascii_lowercase
    length = len(phrase)
    for i in phrase:
        if i == letter:
            count_letters = count_letters + 1
        elif i == search_letter:
            count_letters = count_letters + 1
            count_occurance = count_occurance + 1
        else:
            count_letters = count_letters + 0

    return count_letters, count_occurance

1 个答案:

答案 0 :(得分:1)

此行有问题:

if i == letter:

您已通过letterstring.ascii_lowercase分配了一个包含所有小写字母的字符串。但是i只是一个字母。您可以改用:

if i in letter:
    # ...

检查字符串的成员资格需要O( n )时间。您不妨使用set通过转换将其预先减少为O(1):

letter = set(string.ascii_lowercase)

然后,您需要对if语句的顺序进行反向,以便对search_letter的检查优先。否则,如果search_letter中存在letter,则将永远不会满足第二个条件。

for i in phrase:
    if i == search_letter:
        count_letters = count_letters + 1
        count_occurance = count_occurance + 1
    elif i in letter:
        count_letters = count_letters + 1

请注意以下几行是多余的,您可以放心地删除它们:

else:
    count_letters = count_letters + 0