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

Python字符串重复字符检测代码异常排查:bookkeeper判断错误

问题分析与修复方案

问题描述

编写了两个函数、一个测试列表和一个for循环:

  • histogram函数:返回字符串中各字符的重复次数字典
  • has_duplicates函数:判断传入字符串是否包含重复字符
  • 测试逻辑:遍历列表中的字符串,存在重复则输出[字符串] has duplicates,否则输出[字符串] has no duplicates

但运行时,字符串"bookkeeper"被错误判定为无重复字符(实际有三组重复),其余字符串判断正常。

错误原因

问题出在has_duplicates函数的循环逻辑里:

def has_duplicates(str):
    value_of_dict = histogram(str).values()
    for i in value_of_dict:
        if i > 1:
            return True
        else:
            return False

这个循环只检查第一个字符的计数,如果第一个字符计数为1,就直接返回False,不会继续遍历后续字符的计数。比如"bookkeeper"的第一个字符是'b',计数为1,函数立刻返回False,完全没检查后面的'o'、'k'、'e'这些重复字符。

修复方案

修改has_duplicates函数,只有当遍历完所有字符计数,确认没有大于1的情况时,才返回False;只要遇到一个计数大于1的情况,就返回True。

修复后的函数代码:

def has_duplicates(str):
    value_of_dict = histogram(str).values()
    for i in value_of_dict:
        if i > 1:
            return True
    # 遍历完所有值都没找到大于1的,才返回False
    return False

完整修复后代码

test_dups = ["zzz","dog","bookkeeper","subdermatoglyphic","subdermatoglyphics"] 

def histogram(s):
     d = dict()
     for c in s:
          if c not in d:
               d[c] = 1
          else:
               d[c] += 1
     return d 

def has_duplicates(str):
    value_of_dict = histogram(str).values()
    for i in value_of_dict:
        if i > 1:
            return True
    return False

for i in test_dups:
    if has_duplicates(i):
        print(i, "has duplicates")
    else:
        print(i, "has no duplicates")

运行后,"bookkeeper"会被正确判定为存在重复字符。

内容的提问来源于stack exchange,提问作者Wahid Ahmad Rustaqi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:42:48