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
相关产品推荐
相关产品推荐

