【问题标题】:one or more most frequent letter in string python字符串python中一个或多个最常见的字母
【发布时间】:2015-07-09 22:31:53
【问题描述】:

问题要求我返回一个小写字符串,其中按字母顺序在 s 中出现最频繁的字母。到目前为止,我有:

def mostFrequentLetter(s):
    allchar = ''.join(sorted(s))
    temp = s.replace(" ","")
    max = None
    maxchar = None
    for alph in allchar.lower():
        charcount = temp.count(alph)
        if alph not in string.ascii_letters: continue
        elif charcount > max:
            max = charcount
            max = alph
        elif charcount == max:
            max2 = charcount            
            max2 = alph
            max.append(max2)
    return max

如果我输入'aaaabbbb',它应该给我'ab',但它只给我'a'。我该如何解决这个问题?

【问题讨论】:

  • formatyourcodeformatyourcodeformatyourcode
  • 对不起第一次使用
  • 我不认为我可以使用计数器或设置。没有他们能做到吗?
  • @redbook0301 我添加了一个不使用Counter的示例。

标签: python string


【解决方案1】:

你可以使用内置的collections.Counter:

from collections import Counter

def most_frequent_letter(s):
    counter = Counter(s)
    letter, max_count = next(counter.most_common())
    letters = sorted(letter
                     for letter, count in counter.most_common()
                     if count == max_count)
    return ''.join(letters)

如果由于某种原因你不能使用Counter,你可以使用default dictionary

from collections import defaultdict

def most_frequent_letter(s):
    counter = defaultdict(int)
    for char in s:
        counter[char] += 1
    max_count = max(counter.values())
    letters = sorted(letter
                     for letter, count in counter.items()
                     if count == max_count)
    return ''.join(letters)

【讨论】:

    【解决方案2】:

    我建议使用set() 函数,这样您就不会多次检查重复的字符。

    def mostFrequentLetter(s):
        return ''.join(sorted(sorted((c for c in set(s) if c in string.ascii_letters), key=s.count, reverse=True)[:2]))
    

    这首先将字符串转换为set,消除重复。然后它根据每个元素在原始字符串中出现的频率以相反(降序)顺序对 set 进行排序。最后,它将排序后的元素连接成一个字符串并返回。

    >>> s = 'abbbbbbbbccddddddddddddddddd'
    >>> mostFrequentLetter(s)
    'bd'
    

    【讨论】:

    • 我把他的要求理解为需要找到s中出现频率最高的两个字母,然后按字母顺序返回。
    • 哦,我明白了 - 我会解决的。
    • 你的解释更有趣!
    【解决方案3】:

    其他答案更pythonic。对于您的代码,尽管您犯了一些错误。在下面代码的cmets中看到它们

    def mostFrequentLetter(s):
        allchar = ''.join(sorted(s))
        temp = s.replace(" ","")
        max = None
        maxchar = ""
        for alph in set(allchar.lower()):
            charcount = temp.count(alph)
            if alph not in string.ascii_letters: continue
            elif charcount > max:
                max = charcount
                maxchar+=alph #max = alph sets max as alph. You need to
                              #append the maximum occuring character, not set it as max
            elif charcount == max:
                maxchar+=alph  # max2 is not really needed. Its not being used anywhere else.
                               # In fact this whole clause can be refactored by setting charcount >= max above.
                               # I am still leaving it to be in line with what you wrote
        return maxchar
    
    print mostFrequentLetter("aaaabbbb")
    

    【讨论】:

      【解决方案4】:

      这里,适用于您提供的代码且不使用 Set 的解决方案:)

      def mostFrequentLetter(s):
          allchar = ''.join(sorted(s))
          temp = s.replace(" ","")
          max = None
          maxchar = None
          for alph in allchar.lower():
              charcount = temp.count(alph)
              if alph not in string.ascii_letters: continue
              elif charcount > maxchar:
                  maxchar= charcount
                  max= alph
              elif charcount == maxchar and alph not in max:          
                  max+=alph
          return max
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-13
        • 1970-01-01
        • 1970-01-01
        • 2015-12-01
        • 1970-01-01
        • 2013-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多