Checkio-The most wanted letter-Solution

虽然最近一直在玩Chekio,但是都没有把东西分享出来。

也比较懒...就慢慢更新...

还蛮推荐在Checkio上学习python的。就是通过一个个的小测试来完成任务。

难度:Elementary

##The most wanted letter

##就是从一堆字符串中找到次数最多的字母

##次数相同的,使用最小的字母

举例:

assert checkio("Hello World!") == "l", "Hello test"
assert checkio("How do you do?") == "o", "O is most wanted"
assert checkio("One") == "e", "All letter only once."
assert checkio("Oops!") == "o", "Don't forget about lower case."
assert checkio("AAaooo!!!!") == "a", "Only letters."
assert checkio("abe") == "a", "The First."


##################################答案分界线###########################################3

def checkio(text):
    text=text.lower()
    finallist=[]
    for letter in text:
        templist=[]
        if letter not in templist and letter.isalpha():
            templist.append(letter)
            templist.append(text.count(letter))
            finallist.append(templist)
    finallist=sorted(finallist,key=lambda finallist:(-finallist[-1],finallist[0]))
    return(finallist[0][0])
if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio("Hello World!") == "l", "Hello test"
    assert checkio("How do you do?") == "o", "O is most wanted"
    assert checkio("One") == "e", "All letter only once."
    assert checkio("Oops!") == "o", "Don't forget about lower case."
    assert checkio("AAaooo!!!!") == "a", "Only letters."
    assert checkio("abe") == "a", "The First."
    print("Start the long test")
    assert checkio("a" * 9000 + "b" * 1000) == "a", "Long."
    print("The local tests are done.")

思路比较简单:

通过每个字母的统计,然后最后使用sorted函数排序,第一按照次数,第二按照字母的顺序返回值。

别人的最佳答案:

import string
def checkio(text):
    text = text.lower()
    return max(string.ascii_lowercase, key=text.count)

查了一下string.ascii_lowercase跟string.lowercase应该是一样的。但是我用python3上使用了ascii_lowercase报错,string模块没有lowercase。

使用string.ascii_lowercase就是还会根据字母的顺序进行排列。

猜你喜欢

转载自blog.csdn.net/cyx441984694/article/details/80470910