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

Python不使用def实现hello子序列匹配,输入特定值异常求bug排查

Bug排查结果

你改写后的代码存在两个问题:

  • 缺失输入读取逻辑:原代码通过input()获取用户输入的字符串,改写版本未定义string变量,运行时会触发变量未定义错误
  • 匹配完成后未终止循环:原函数版匹配到完整hello后会直接return终止逻辑,而改写版匹配完成后仍会继续遍历后续字符,此时counter_hello的值等于hello的长度5,后续访问hello[counter_hello]会触发索引越界错误,导致输出异常。

修复后代码

hello = "hello"
counter_hello = 0
bool_hello = False
# 补充输入读取逻辑
string = input()

for letter in string:
    if letter == hello[counter_hello]:
        counter_hello += 1
    if counter_hello == len(hello):
        bool_hello = True
        # 匹配完成直接跳出循环,避免索引越界
        break

print("YES" if bool_hello else "NO")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:36:10