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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:55:21