def lookup_cell(self, column, row):
return(self.puzzle[row-1][column-1])
def lookup_column(self, column):
output = []
for i in range(9):
output.append(self.lookup_cell(column, i+1))
return output
def check_puzzle(self):
valid = True
#check all the rows
for i in range(1,10):
row = self.lookup_row(i)
while 0 in row: row.remove(0)
for i in range(1,10):
if row.count(i) > 1:
valid = False
#check all the columns
for i in range(1,10):
print(i)
print(easy.lookup_column(i))
puzzle = '''0,9,0,7,5,1,0,2,3 /n
2,1,8,6,0,3,7,5,4 /n
0,0,0,4,0,2,0,0,0 /n
1,0,0,0,0,0,0,9,2 /n
0,0,0,5,0,0,3,8,0 /n
3,0,0,8,2,0,5,0,6 /n
0,0,0,0,7,0,0,4,8 /n
0,4,9,0,0,0,0,7,0 /n
0,2,0,0,0,5,6,3,1 '''
easy = Sudoku(puzzle)
这里的代码可以正常工作并正确打印拼图的列:
for i in range(1,10):
print(easy.lookup_column(i))
在运行时出现错误,我将在下面添加该错误:
easy.check_puzzle()
1 [9, 2, 4, 1, 5, 3, 7, 4, 2] 2 [7, 1, 2, 9, 3, 8, 4, 9, 5] 3
Traceback (most recent call last):
File "/Users/ellis/Desktop/Sudoku.py", line 121, in <module>
easy.check_puzzle()
File "/Users/ellis/Desktop/Sudoku.py", line 81, in check_puzzle
print(easy.lookup_column(i))
File "/Users/ellis/Desktop/Sudoku.py", line 65, in lookup_column
output.append(self.lookup_cell(column, i+1))
File "/Users/ellis/Desktop/Sudoku.py", line 19, in lookup_cell
return(self.puzzle[row-1][column-1])
IndexError: list index out of range
答案 0 :(得分:0)
您的代码在class方法之外运行,因为
for i in range(1,10):
print(easy.lookup_column(i))
没有拨打电话
def lookup_cell(self, column, row):
return(self.puzzle[row-1][column-1]
您发布的追溯表明,上面的代码正在导致问题,您访问的对象超出其范围
答案 1 :(得分:0)
我不确定您要完成什么,但是为什么不使用列表而不是字符串呢?
尝试一下:
class Sudoku(object):
def __init__(self,puzzle):
self.puzzle = puzzle
print("Inside class; column lookup")
for i in range(1,10):
print('Column {0} ='.format(i),self.lookup_column(i))
self.check_puzzle()
def lookup_cell(self, column, row):
return self.puzzle[row-1][column-1]
def lookup_row(self,row):
output = []
for i in range(9):
output.append(self.lookup_cell(i+1, row))
return output
def lookup_column(self, column):
output = []
for i in range(9):
output.append(self.lookup_cell(column, i+1))
return output
def check_puzzle(self):
valid = True
#check all the rows
for i in range(1,10):
row = self.lookup_row(i)
while 0 in row: row.remove(0)
for i in range(1,10):
if row.count(i) > 1:
valid = False
puzzle = [
[0,9,0,7,5,1,0,2,3],
[2,1,8,6,0,3,7,5,4],
[0,0,0,4,0,2,0,0,0],
[1,0,0,0,0,0,0,9,2],
[0,0,0,5,0,0,3,8,0],
[3,0,0,8,2,0,5,0,6],
[0,0,0,0,7,0,0,4,8],
[0,4,9,0,0,0,0,7,0],
[0,2,0,0,0,5,6,3,1]]
easy = Sudoku(puzzle)
print("Outside class; column lookup")
for i in range(1,10):
print('Column {0} ='.format(i),easy.lookup_column(i))
easy.check_puzzle()