Python:编写符合规则的max_index函数及错误代码修正求助
问题分析与修正
你的代码存在两个核心问题:
- 循环里
index每次无条件自增,最终返回的是列表长度,而非最大值的索引 - 找到更大值时仅更新了最大值,没有同步更新对应的索引
按照要求,我们可以用变量手动跟踪当前索引,仅当遇到严格更大的元素时才更新最大值和索引(这样重复的最大值会自动保留最早出现的最小索引),修正后的代码如下:
def max_index(lon): """ input is a list of numbers. returns the index of the largest number in the list """ if not lon: # 处理空列表的边界情况,提升代码健壮性 raise ValueError("Empty list has no maximum index") current_max = lon[0] max_idx = 0 current_idx = 0 for num in lon: if num > current_max: current_max = num max_idx = current_idx current_idx += 1 return max_idx
关键逻辑说明
- 初始化时将第一个元素设为当前最大值,对应索引设为0
- 遍历元素时,只有当前元素比当前最大值大时,才更新最大值和索引——遇到重复的最大值时不会修改
max_idx,自然保留最早出现的最小索引 - 用
current_idx手动跟踪遍历位置,完全符合不能使用range/enumerate的要求
测试示例
print(max_index([1, 3, 2, 3])) # 输出1,第一个3出现在索引1的位置 print(max_index([5, 4, 3])) # 输出0 print(max_index([-1, -3, -2])) # 输出0
内容的提问来源于stack exchange,提问作者Taylor Reid
相关产品推荐
相关产品推荐

