首页 > 解决方案 > python迷宫求解器列表索引超出范围错误

问题描述

我正在尝试观看一段视频,该视频展示了如何对数独求解器进行编程,但是当该函数出现 true 时,我得到了一个错误。当输入不是有效选项时,我确实得到了错误的返回,所以我想这确实有效。

import numpy as np

grid = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
        [6, 0, 0, 1, 9, 5, 0, 0, 0],
        [0, 9, 8, 0, 0, 0, 0, 6, 0],
        [8, 0, 0, 0, 6, 0, 0, 0, 3],
        [4, 0, 0, 8, 0, 3, 0, 0, 1],
        [7, 0, 0, 0, 2, 0, 0, 0, 6],
        [0, 6, 0, 0, 0, 0, 2, 8, 0],
        [0, 0, 0, 0, 8, 0, 0, 7, 9]]


def possible(y, x, n):
    global grid
    for i in range(0, 9):
        if grid[y][i] == n:
            return False
    for i in range(0, 9):
        if grid[i][x] == n:
            return False
    x0 = (x // 3) * 3
    y0 = (y // 3) * 3
    for i in range(0, 3):
        for j in range(0, 3):
            if grid[y0 + i][x0 + j] == n:
                return False
    return True

print(possible(4, 4, 5))

这是我收到的错误:

Traceback (most recent call last):
  File "sudoku.py", line 44, in <module>
    print(possible(4, 4, 5))
  File "sudoku.py", line 19, in possible
    if grid[i][x] == n:
IndexError: list index out of range

Process finished with exit code 1

标签: pythonsudoku

解决方案


最后一行通常是您应该首先查看的位置:IndexError: list index out of range. 同样从堆栈跟踪中,您可以看到错误发生的确切位置。

您基本上是在尝试访问具有不存在索引的元素。这通常发生在索引>=(大于或等于)列表的长度时,就像您的情况一样。

顺便说一句,您可以通过简单地使用类似for element in my_list. 但是,如果您有充分的理由使用索引,通常最好使用for i in range(len(my_list)),而不是到处硬编码列表的长度。


推荐阅读