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

Python返回列表首个小于自身索引的整数索引,现有代码如何修复

问题原因

你当前的代码逻辑完全偏离了需求:需求是找第一个数值小于自身对应索引的元素索引,而你的代码是在找列表最小值的索引,且最小值出现多次时会返回列表,也不符合函数要求返回整数的约定。

修复后代码

def smaller_index(items: list[int]) -> int:
    """
    Return the index of the first integer in items that is less than its index,
    or -1 if no such integer exists in items.
    
    >>> smaller_index([2, 5, 7, 99, 6])
    -1
    >>> smaller_index([-5, 8, 9, 16])
    0
    >>> smaller_index([5, 8, 9, 0, 1, 3])
    3
    """
    # 遍历索引和对应元素
    for index, value in enumerate(items):
        # 遇到第一个满足条件的直接返回索引
        if value < index:
            return index
    # 遍历完所有元素都没符合条件的,返回-1
    return -1

校验方法

运行如下代码即可验证所有给定测试用例是否通过:

import doctest
doctest.testmod()

没有输出就代表所有测试用例执行正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:57:01