You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

most_popular_character函数返回值异常,请求代码修正建议

问题需求

实现函数most_popular_character(my_string):

  • 接收字符串参数my_string,返回出现频率最高的字符
  • 若多个字符频率相同,返回ASCII值更小的字符
  • 大小写字母视为不同(如'A' < 'a'),输入仅含英文字母且非空

示例:

  1. most_popular_character("HelloWorld") 返回 'l'
  2. most_popular_character("gggcccbb") 返回 'c'(解释:c和g均出现3次,但c的ASCII值更小)

现有代码

def most_popular_character(my_string):
   char_count = {} # define dictionary
   for c in my_string:
      if c in char_count: #if c is in the dictionary:
         char_count[c] = 1
      else: # if c isn't in the dictionary - create it and put 1
         char_count[c] = 1

   sorted_chars = sorted(char_count) # sort the dictionary
   char_count = char_count.keys() # place the dictionary in a list

   max_per = 0
   for i in range(len(sorted_chars) - 1):
      if sorted_chars[i] >= sorted_chars[i+1]:
         max_per = sorted_chars[i]
         break
   return max_per

当前函数返回0,问题集中在最后一段循环和判断逻辑,需要调整代码。


问题分析

现有代码存在多处核心逻辑错误:

  • 计数逻辑失效:遍历字符串时,无论字符是否已存在,都将计数设为1,根本没有累加出现次数,导致所有字符计数都是1,无法统计真实频率。
  • 字典数据丢失:执行char_count = char_count.keys()后,原本存储计数的字典被替换成键列表,完全丢失了关键的频率信息。
  • 结果选择逻辑完全偏离需求:最后一段循环的判断既没有比较字符频率,也没处理ASCII值优先级,逻辑混乱导致返回错误结果。

修正后的代码
def most_popular_character(my_string):
    char_count = {}
    # 正确统计每个字符的出现次数
    for c in my_string:
        if c in char_count:
            char_count[c] += 1
        else:
            char_count[c] = 1
    
    # 排序规则:先按频率降序,频率相同则按ASCII值升序
    sorted_chars = sorted(char_count.items(), key=lambda x: (-x[1], x[0]))
    
    # 返回排序后的第一个字符
    return sorted_chars[0][0]

代码说明

  • 计数修正:将原代码中错误的char_count[c] = 1改为char_count[c] += 1,实现对字符出现次数的正确累加。
  • 排序逻辑适配需求:通过sorted的key参数,-x[1]确保频率高的字符排在前面;x[0]保证频率相同时,ASCII值更小的字符优先。
  • 结果直接返回:排序后的第一个元素就是符合要求的目标字符,直接返回即可。

内容的提问来源于stack exchange,提问作者Libi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:15:41