python - 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
解决方案
最后一行通常是您应该首先查看的位置:IndexError: list index out of range
. 同样从堆栈跟踪中,您可以看到错误发生的确切位置。
您基本上是在尝试访问具有不存在索引的元素。这通常发生在索引>=
(大于或等于)列表的长度时,就像您的情况一样。
顺便说一句,您可以通过简单地使用类似for element in my_list
. 但是,如果您有充分的理由使用索引,通常最好使用for i in range(len(my_list))
,而不是到处硬编码列表的长度。
推荐阅读
- c# - 选中数组中的复选框时更新标签
- python-3.x - 我可以在等待子进程 Popen 的同时在另一个线程中工作吗
- gitlab - 如何修复 Permission denied (publickey) onGitlab?
- python - 检查数百万搜索查询中是否存在大量单词的有效方法
- c++ - 类类型向量的打印内容
- python-3.x - 代码不起作用,清除错误消息,但找不到源
- testing - 如何在测试环境中使用 PageSpeed?(密码保护)
- python - 表面对象在 Matplotlib 中错误地相互遮挡
- angular - Ionic 4 RouterLink 不适用于带有选项卡和侧边菜单的应用程序
- angular7 - 为 Angular 7 中的特定组件生成单独的构建文件