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

实现EnhancedString类中基于while循环的character_frequency字符统计方法

问题需求

现有如下定义的EnhancedString类,需要实现其中的character_frequency方法:

  • 必须使用while循环遍历类的_contents属性
  • 最终返回字典,键为字符串内的所有字符,值为对应字符的出现次数

已有类的基础代码如下:

class EnhancedString:
    def __init__(self, contents):
        self._contents = str(contents)
    def __str__(self):
        return str(self._contents)
    def __len__(self):
        return len(self._contents)
    def set_contents(self, contents):
        self._contents = str(contents)
    def get_contents(self):
        return self._contents
    # 待实现的方法
    def character_frequency(self):
        """
        返回存储字符串内所有字符出现次数的字典,键为字符,值为对应出现次数,必须用while循环遍历字符串
        :return: 字符为键、出现次数为整数值的字典
        示例调用:
            >>> c = EnhancedString("")
            >>> print(c.character_frequency())
            {}
            >>> a = EnhancedString("abcdefg")
            >>> print(a.character_frequency())
            {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1}
            >>> b = EnhancedString("aabcdefgaa")
            >>> print(b.character_frequency())
            {'a': 4, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1}
        """
完整实现代码

补全后的character_frequency方法如下:

def character_frequency(self):
        """
        返回存储字符串内所有字符出现次数的字典,键为字符,值为对应出现次数,必须用while循环遍历字符串
        :return: 字符为键、出现次数为整数值的字典
        示例调用:
            >>> c = EnhancedString("")
            >>> print(c.character_frequency())
            {}
            >>> a = EnhancedString("abcdefg")
            >>> print(a.character_frequency())
            {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1}
            >>> b = EnhancedString("aabcdefgaa")
            >>> print(b.character_frequency())
            {'a': 4, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1}
        """
        freq_dict = {}
        index = 0
        content_length = len(self._contents)
        while index < content_length:
            current_char = self._contents[index]
            if current_char in freq_dict:
                freq_dict[current_char] += 1
            else:
                freq_dict[current_char] = 1
            index += 1
        return freq_dict
实现逻辑说明
  • 先初始化空字典freq_dict存储字符频率统计结果
  • 定义索引变量index初始值为0,作为遍历字符串的游标
  • while循环的终止条件为索引值大于等于字符串总长度,保证每个字符都被遍历到
  • 每次循环取出当前索引对应的字符,判断是否已存在于字典中:存在则计数加1,不存在则新增键值对,计数设为1
  • 遍历完成后直接返回统计字典即可,所有测试用例运行结果和预期完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:06:03