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

Python递归统计两个字符串中字符a和b的总出现次数

问题解答

原代码存在的问题

  • 变量名错误:递归调用时误用了不存在的变量string,实际第一个入参为string1,运行会直接报错
  • 返回值不符合要求:原设计仅返回单个数值(a的统计结果),需求要求返回(a总个数, b总个数)的元组
  • 未覆盖统计目标:仅统计了字符a的出现次数,未统计b
  • 未处理第二个输入字符串:递归逻辑完全没有用到入参string2

修改后的完整代码

def counting(string1, string2):
    # 递归基准条件:两个字符串都处理完毕,返回初始计数
    if not string1 and not string2:
        return (0, 0)
    # 第一个字符串处理完后,切换到处理第二个字符串
    if not string1:
        return counting(string2, "")
    # 统计当前第一个字符的a、b计数增量
    current_a = 1 if string1[0] == 'a' else 0
    current_b = 1 if string1[0] == 'b' else 0
    # 递归处理剩余内容,累加计数
    rest_a, rest_b = counting(string1[1:], string2)
    return (current_a + rest_a, current_b + rest_b)

测试验证

调用counting('aabb', 'bbba'),返回结果为(3, 5),符合示例要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 22:15:00