【问题标题】:Return most frequent letter lowercase and in alphabetical order返回最常用的小写字母并按字母顺序排列
【发布时间】:2015-09-28 15:40:54
【问题描述】:

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

到目前为止,我有这个:

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

【问题讨论】:

    标签: python string list function


    【解决方案1】:

    最常见的字母

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

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

    【讨论】:

    • 我想他想知道你的柜台到底是怎么做的
    • def mostFrequentLetter(s, n=1): 但是有没有办法在没有 n=1 的情况下做到这一点?因为我在网上找到的问题只使用了defmostFrequentLetter(s)
    • 我还需要返回重复次数最多的一个或多个字母。例如: mostFrequentLetter("ZgVhyaBbv") == "bv")
    • @Aleish 好的。代码现在在答案中。
    • @John1024 抱歉,您知道我不需要使用计数器的其他方式
    【解决方案2】:
    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))
    

    【讨论】:

    • 它可以工作,但它只能打印一个字母。该代码也应该打印多个字母。
    • 很高兴解释为什么这会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多