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

时间:2015-07-10 02:25:13

标签: python string list function

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

到目前为止,我有这个:

def mostFrequentLetter(s):        
    s1 = sorted(s)    
    s1 = s.lower()       
    for x in s1:
        if s1.isAlpha == True:

2 个答案:

答案 0 :(得分: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最常见的字母

这将在字符串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)))

示例:

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

如何运作

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

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

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

答案 1 :(得分: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))
相关问题