我的代码应该正常解决数独,我的文本文件错了吗?
我收到此错误:
D:\ Oneg \ Python \ sudoku2.py",第85行,在estDansSousMatrice中 if grille [i] [j] == v:IndexError:列表索引超出范围
309000400
200709000
087000000
750060230
600904008
028050041
000000590
000106007
006000104
这是我的代码:
def estDansSousMatrice(grille, l, c, v):
bc = (c / 3) * 3
bl = (l / 3) * 3
for i in range(int(bl), int(bl) + 3):
for j in range(int(bc), int(bc) + 3):
if grille[i][j] == v:
return True
return False
我的文字打开了:
def charge(nom_du_fichier):
mon_fichier = open(nom_du_fichier, "r")
x = [[0] * 9 for i in range(9)]
for j in range(9):
line = mon_fichier.readline().split(" ")
for i in range(len(line)):
if line[i].isdigit():
x[j][i] = int(line[i])
else:
return(x)
答案 0 :(得分:0)
在Python 3中,表达式(c / 3) * 3
始终是一个浮点值,其值与c
相同。如果你想要向下舍入到最接近的三的倍数,你需要在括号中的部分显式调用int
,或者使用//
运算符来请求“floor”除法而不是“true” “除法(来自/
运算符)。
我怀疑这是导致索引问题的原因。当您调用函数的坐标位于最后三行或列中时,您最终会得到一个超出范围的索引。
尝试使用:
bc = c // 3 * 3 # the parentheses were not necessary
bl = l // 3 * 3