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

Python判断列表含1,2,3连续序列代码运行失败,问题出在哪里?

代码错误点汇总
  • 文档注释与实际需求不符:注释中描述的功能是检测1,3,5序列是否存在,和你要实现的检测1,2,3连续序列的需求不一致,会给后续代码维护带来误解
  • 循环遍历范围错误:要连续取3个相邻元素,最大的起始下标应为len(nums)-3,当前你用的range(len(nums)-1)范围过大,当i取到len(nums)-2时,访问第三个元素会超出列表索引边界,触发越界报错,正确范围应为range(len(nums)-2)
  • 第三个元素的索引写法错误:代码中写的nums[+2]等价于nums[2],永远固定取列表下标为2的元素,不是当前i位置往后两位的元素,正确写法是nums[i+2]
修正后的代码
def has123(nums): 
    """Takes a list of one or more ints nums and returns True if 
    the sequence 1, 2, 3 appears in the list somewhere and false 
    otherwise"""   
    for i in range(len(nums)-2): 
        if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3:
            return True
    return False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:09:04