Python指定位置字符频率统计代码部分输入结果错误排查
问题定位与修复
错误原因
- 未跳过已经被标记为
0的无效遍历位置:当外层循环遍历到已经被标记为统计过的0位置时,仍然会进入内层循环匹配其他位置的0,导致count被无意义累加。 - 计数变量重置时机错误:只有当打印统计结果时才会重置
count为1,遍历到无效0位置时累加的错误count值会被保留,影响后续有效字符的统计结果。
修复方案
- 外层循环每次遍历首先判断当前字符是否为
0,如果是直接跳过本次循环,不执行统计逻辑。 - 将计数变量
count的初始化移到外层循环内部,每次处理有效字符前重置为1,避免历史值干扰。 - 额外优化:避免使用
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
相关产品推荐
相关产品推荐

