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

