python 练习 - 6

一个字符串中出现次数最多的字母,并返回(打印)之

原文题目来自(https://py.checkio.org/mission/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.

def Most_wanted_letter(text):
    text = text.lower()
    l = []
    l3 = []
    t = 0
    for i in range(len(text)):
        if text[i].isalpha():
            l.append(text[i])

    for j in range(len(l)):
        if l[j] not in l3:
            l3.append(l[j])
            l2 = l[:]
            k = 0
            while l[j] in l2:
                l2.remove(l[j])
                k = k + 1
        else:
            continue
        if t < k or (t == k and l[j] <= s):
            t = k
            s = l[j]
    print(s)



print("出现次数最多的字母是:", end='')
Most_wanted_letter("23kjdgaoreg[a,gArhrga  dga")

基本思路:将字符串转换成小写,并放入到一个列表中,然后对列表进行操作。remove一个元素,然后利用while 循环判断是否还在列表中,并用计数器k计数,l3的作用是存放已经去除的元素,并在元素重复出现时跳过,l2是一个临时列表,它复制了l列表,用来进行去除元素的操作。

猜你喜欢

转载自blog.csdn.net/jiayangwu/article/details/79709461