返回出现最频繁的小写字母,并按字母顺序排列。

3
这是我在网上发现的一个问题。 mostFrequentLetter(s) 接受一个字符串 s,并返回按字母顺序排序的小写字符串,其中包含出现频率最高的字母。对于此函数,应忽略大小写(因此“A”和“a”被视为相同)。仅考虑字母(不包括标点符号或空格)。您不需要担心此函数的效率。
到目前为止,我有这个:
def mostFrequentLetter(s):        
    s1 = sorted(s)    
    s1 = s.lower()       
    for x in s1:
        if s1.isAlpha == True:
2个回答

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]))

示例:

>>> mostFrequentLetter("ZgVhyaBbv")
'bv'
>>> mostFrequentLetter("aaabbcc????")
'a'

出现频率最高的n个字母

这将会提供字符串s中出现频率最高的n个字母,并按照字母表顺序进行排序:

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)))

例子:

>>> mostFrequentLetter('aabbccadef?!', n=1)
'a'
>>> mostFrequentLetter('aabbccadef?!', n=3) 
'abc'

工作原理

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

    This converts string s to lower case and then just the letters from that string.

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

    This creates a Counter instance for those letters. We will use the method most_common to select the most common letters. To get the three most common letters, for example, we can use:

    >>> data.most_common(3)
    [('a', 3), ('c', 2), ('b', 2)]
    

    In our case, we are not interested in the counts, only the letters, so we have to manipulate this output.

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

    This selects the n most common letters.

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

    This sorts alphabetically the n most common letters.

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

    This joins most common letters back into a string and returns them.

最常用的字母(不使用包)

如果不能使用 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)

我认为他想确切地了解你的计数器如何执行该过程。 - rassa45
def mostFrequentLetter(s, n=1): 但是有没有不使用n=1的方法呢?因为我在网上找到的问题只使用了defmostFrequentLetter(s) - Aleish
还有,我需要返回重复次数最多的字母或字母组合。 例如: mostFrequentLetter("ZgVhyaBbv") == "bv" - Aleish
@Aleish 好的,现在答案中已经有代码了。 - John1024
@John1024 抱歉,你知道其他不需要使用Counter的方法吗? - Aleish
@Aleish 我添加了一个避免使用 Counter 的版本。 - John1024

0
def mostFrequentLetter(s):
    s1 = s.lower()
    new = set(s1)
    mod={}

    for item in new:
        if item.isalpha():
            mod[item]=s1.count(item)

    frequent = sorted (mod,key = mod.get)
    return list(reversed(frequent))

它能工作,但只能打印一个字母。该代码应该也能打印多个字母。 - Aleish
最好能解释一下为什么这样做有帮助。 - Wtower

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接