Python实现连续s字符检测代码运行异常如何修复
问题根因
1. 输出逻辑完全反转
你初始化flag = True,匹配到连续s时将flag设为False,最后却通过if(not flag)判断输出no hiss,直接导致三类异常现象:
- 匹配到连续
s时,先打印hiss,后续又触发not flag的判断逻辑额外打印no hiss - 未匹配到连续
s时,flag保持为True,not flag为假,no hiss无输出
2. 字符校验存在遗漏
你遍历用的range(len(word)-1,0,-1)不包含索引为0的第一个字符,若输入第一个字符为非小写字母,不会触发校验逻辑。
3. 遍历逻辑冗余
反向遍历完全没有必要,不仅可读性差,还容易出错。
修复后代码
word = input() # 长度校验 if len(word) > 30: raise Exception("Word too long") # 全字符合法性校验 for c in word: if c not in "abcdefghijklmnopqrstuvwxyz": raise Exception("Invalid Character") # 检查连续s has_consecutive_s = False for i in range(len(word) - 1): if word[i] == "s" and word[i+1] == "s": has_consecutive_s = True break # 输出逻辑 print("hiss" if has_consecutive_s else "no hiss")
极简实现方案
Python字符串原生支持子串存在性判断,不需要手动遍历匹配连续s,可大幅简化代码:
word = input() if len(word) > 30: raise Exception("Word too long") for c in word: if not c.islower(): raise Exception("Invalid Character") print("hiss" if "ss" in word else "no hiss")
内容的提问来源于stack exchange,提问作者JRBros
相关产品推荐
相关产品推荐

