【checkio】Python学习--The Most Wanted Letter

You are given a text, which contains different english letters and punctuation symbols. You should find the most frequent letter in the text. The letter returned must be in lower case.
While checking for the most wanted letter, casing does not matter, so for the purpose of your search, "A" == "a". Make sure you do not count punctuation symbols, digits and whitespaces, only letters.

If you have two or more letters with the same frequency, then return the letter which comes first in the latin alphabet. For example -- "one" contains "o", "n", "e" only once for each, thus we choose "e".

Input: A text for analysis as a string.

Output: The most frequent letter in lower case as a string.

题目来自  py.checkio.org

My answer:

思路:首先将字符串转化为小写,依次计算每个字符出现的次数,保存最大值以及相应字符

def checkio(text):

    text=text.lower()
    maxChar=''
    maxCount=0
    for i in range(97,123):
        countText=text.count(chr(i))
        if countText>maxCount:
            maxCount=countText
            maxChar=chr(i)
    #replace this for solution

    return maxChar

Other answer:

import string

def checkio(text):
    """
    We iterate through latyn alphabet and count each letter in the text.
    Then 'max' selects the most frequent letter.
    For the case when we have several equal letter,
    'max' selects the first from they.
    """
    text = text.lower()
    return max(string.ascii_lowercase, key=text.count)

你可能感兴趣的:(checkio)