返回最常见的小写字母和字母顺序

Ale*_*ish 3 python string function list

这是我在互联网上发现的问题.mostFrequentLetter(s)接受一个字符串s,并返回一个小写字符串,其中包含按字母顺序排列的最常出现的字母.应该忽略大小写(因此对于此函数,"A"和"a"被认为是相同的).只考虑字母(没有标点符号或空格).您无需担心此功能的效率如何.

到目前为止我有这个:

def mostFrequentLetter(s):        
    s1 = sorted(s)    
    s1 = s.lower()       
    for x in s1:
        if s1.isAlpha == True:
Run Code Online (Sandbox Code Playgroud)

Joh*_*024 5

最常见的信件

from collections import Counter

def mostFrequentLetter(s):
    mc = Counter(c for c in s.lower() if c.isalpha()).most_common()
    return ''.join(sorted(c[0] for c in mc if c[1] == mc[0][1]))
Run Code Online (Sandbox Code Playgroud)

例子:

>>> mostFrequentLetter("ZgVhyaBbv")
'bv'
>>> mostFrequentLetter("aaabbcc????")
'a'
Run Code Online (Sandbox Code Playgroud)

n最常见的字母

这将提供n字符串中最常用的字母s,按字母顺序排序:

from collections import Counter

def mostFrequentLetter(s, n=1):
    ctr = Counter(c for c in s.lower() if c.isalpha())
    return ''.join(sorted(x[0] for x in ctr.most_common(n)))
Run Code Online (Sandbox Code Playgroud)

例子:

>>> mostFrequentLetter('aabbccadef?!', n=1)
'a'
>>> mostFrequentLetter('aabbccadef?!', n=3) 
'abc'
Run Code Online (Sandbox Code Playgroud)

这个怎么运作

  • c for c in s.lower() if c.isalpha()

    这会将字符串转换s为小写,然后只转换为该字符串中的字母.

  • ctr = Counter(c for c in s.lower() if c.isalpha())

    这会为这些字母创建一个Counter实例.我们将使用该方法most_common选择最常见的字母.例如,要获得三个最常见的字母,我们可以使用:

    >>> data.most_common(3)
    [('a', 3), ('c', 2), ('b', 2)]
    
    Run Code Online (Sandbox Code Playgroud)

    在我们的例子中,我们对计数不感兴趣,只对字母感兴趣,所以我们必须操纵这个输出.

  • x[0] for x in ctr.most_common(n)

    这将选择n最常见的字母.

  • sorted(x[0] for x in ctr.most_common(n))

    这按字母顺序排列n最常见的字母.

  • return ''.join(sorted(x[0] for x in ctr.most_common(n)))

    这会将大多数常见字母连接回字符串并返回它们.

不使用包的最常见字母

如果我们不能使用collections.Counter,那么试试:

def mostFrequentLetter(s):
    d = {}
    for c in s.lower():
        d[c] = d.get(c, 0) + 1
    mx = max(dict_values())
    return sorted(c for c, v in d.items() if v == mx)
Run Code Online (Sandbox Code Playgroud)