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

编写canConstruct函数报ValueError: substring not found错误原因排查

错误原因

str.index() 方法的特性是:如果传入的子串不存在于当前字符串中,会直接抛出ValueError: substring not found异常,不会返回负值或其他标识。
你的测试用例目标字符串末尾带有字符f,递归到最后target会缩减为仅包含f的字符串,此时遍历wordBank中所有由e组成的单词,都不存在于target中,调用target.index(word)就触发了报错。
另外你用index判断前缀的逻辑本身也存在性能浪费:index会扫描整个字符串查找子串的第一个位置,而你只需要判断字符串开头是否匹配,不需要全串扫描。

修复方案

直接使用Python内置的str.startswith()方法替换前缀判断逻辑即可,该方法专门用于判断字符串是否以指定子串开头,匹配失败会直接返回False,不会抛出异常,性能也更优。
修复后的代码如下:

def canConstruct(target, wordBank):
    # 基线条件:target为空说明已拼接完成
    if target == '':
        return True
    for word in wordBank:
        # 替换为startswith判断前缀
        if target.startswith(word):
            suffix = target.removeprefix(word)
            if canConstruct(suffix, wordBank):
                return True
    return False

print(canConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeef",["e","ee","eee","eeee","eeeee","eeeeee","eeeeeee"]))

运行后会正确返回False,符合预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:24:03