I'm trying to follow a video that shows how to program sudoku solver, but I'm getting an error when a true comes out of the function. I do get a false return when the input is not a valid option, so I guess that does work.
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))
This is the error I'm receiving:
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
The last line is usually where you should first look at: IndexError: list index out of range
. Also from the stacktrace you can see where exactly the error occurs.
You are basically trying to access an element with an index that does not exist. That usually happens when the index is >=
(greater than or equal to) the list's length, as is in your case.
BTW you can iterate a list without using indexes by simply using something like for element in my_list
. However, if you have a good reason to use indexes, it is usually better to use for i in range(len(my_list))
, instead of hard-coding the list's length all over the place.