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

Python指定位置字符频率统计代码部分输入结果错误排查

问题定位与修复

错误原因

  • 未跳过已经被标记为0的无效遍历位置:当外层循环遍历到已经被标记为统计过的0位置时,仍然会进入内层循环匹配其他位置的0,导致count被无意义累加。
  • 计数变量重置时机错误:只有当打印统计结果时才会重置count为1,遍历到无效0位置时累加的错误count值会被保留,影响后续有效字符的统计结果。

修复方案

  1. 外层循环每次遍历首先判断当前字符是否为0,如果是直接跳过本次循环,不执行统计逻辑。
  2. 将计数变量count的初始化移到外层循环内部,每次处理有效字符前重置为1,避免历史值干扰。
  3. 额外优化:避免使用str作为变量名,会覆盖Python内置的字符串类型关键字,同时去掉冗余的map(str, input())写法,input()本身返回的就是可直接转列表的字符串。

修复后代码

input_str = list(input("Enter the string : "))
start_idx = int(input("Enter the location from which the count needs to start : "))
for i in range(start_idx, len(input_str)):
    # 跳过已经统计过的标记位
    if input_str[i] == 0:
        continue
    # 每次统计有效字符前重置计数
    count = 1
    for j in range(i+1, len(input_str)):
        if input_str[i] == input_str[j]:
            count += 1
            input_str[j] = 0
    print(input_str[i], " appears ", count, " times")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:24:03