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

递归实现二维数组峰值查找时触发IndexError错误求助

二维数组递归找峰值的IndexError问题排查

问题概述

编写了递归查找二维数组峰值的代码,运行时触发IndexError: list index out of range错误,代码、输入示例及预期输出如下:

原代码

def find(lst):
    m=len(lst[0])
    n=len(lst)
    j=m//2

    currentRow=[]
    i=0
    while i< len(lst):
        currentRow.append(lst[i][j])
        i+=1

    i=currentRow.index(max(currentRow))

    if j>0 and lst[i][j]<lst[i][j-1]:
        return find([currentRow[:j] for currentRow in lst])
    elif j<m-1 and lst[i][j]<lst[i][j+1]:
        return find([currentRow[j:] for currentRow in lst])
    else:
        return lst[i][j]
lst=[]
while True:
    try:
        lst.append([int(num) for num in input().split()])
    except EOFError:
        break
maxNum=find(lst)
for i in range(len(lst)):
    for j in range(len(lst[0])):
        if lst[i][j]==maxNum:
            print((i,j))

输入示例

10 8 10 10
14 13 12 11
15 9 11 21
16 17 19 20

预期输出

(2, 3)

错误原因分析

触发索引越界的核心原因:

  1. 输入未过滤空行:若输入过程中误按回车产生空行,代码会将空列表添加到lst中,后续递归访问lst[i][j]时,空列表无对应索引元素,直接触发错误。
  2. 未校验行长度一致性:若输入的各行长度不一致,递归分割数组后,某行长度会小于当前访问的列索引j,导致索引越界。
  3. (易混淆问题)递归调用的列表推导式中,循环变量currentRow与外层定义的currentRow列表重名,虽不直接报错,但降低了代码可读性。

修复后的代码

def find(lst):
    m = len(lst[0])
    j = m // 2

    # 提取当前列的所有元素
    current_col = []
    for row in lst:
        current_col.append(row[j])
    
    # 找到当前列最大值所在的行索引
    max_row_idx = current_col.index(max(current_col))

    # 向左递归
    if j > 0 and lst[max_row_idx][j] < lst[max_row_idx][j-1]:
        return find([row[:j] for row in lst])
    # 向右递归
    elif j < m - 1 and lst[max_row_idx][j] < lst[max_row_idx][j+1]:
        return find([row[j:] for row in lst])
    # 找到峰值
    else:
        return lst[max_row_idx][j]

lst = []
while True:
    try:
        line = input().strip()
        # 过滤空行
        if not line:
            continue
        row = [int(num) for num in line.split()]
        lst.append(row)
    except EOFError:
        break

# 校验输入合法性
if not lst:
    print("输入不能为空")
    exit()
row_length = len(lst[0])
for row in lst[1:]:
    if len(row) != row_length:
        print("所有行的元素数量必须一致")
        exit()

max_num = find(lst)
# 遍历原数组找到峰值位置
for i in range(len(lst)):
    for j in range(len(lst[0])):
        if lst[i][j] == max_num:
            print((i, j))

修复说明

  1. 输入处理优化:添加空行过滤逻辑,避免空列表混入lst;增加输入合法性校验,确保所有行长度一致,提前拦截非法输入。
  2. 代码可读性优化:将外层的currentRow改为current_col,列表推导式中用row作为循环变量,避免变量名冲突。
  3. 循环简化:将原有的while循环改为更简洁的for循环,提升代码可读性。

测试验证

使用提供的输入示例运行修复后的代码,可正确输出预期结果(2, 3),无索引越界错误。

内容的提问来源于stack exchange,提问作者CHIN KENG HOW

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:58:14