我在使用 Python 编程方面相对较新。这段代码运行良好,直到我尝试将它变成一个类。我正在为我的数独求解器代码开设课程,练习课程并涉足面向对象的编程。
因此,我从有类似问题的用户那里阅读了一大堆问题,大多数答案是: - 在从所述类调用函数之前先实例化类,但它们似乎都不适用于我的具体示例。
这是我的课:
#assume sudoku is imported as a np.array, white spaces replaced by zeros
class Sudoku():
solution_number = 1
def __init__ (self, sud_arr):
self.sudo = sud_arr
#print(self.sudo)
def possible (self, y, x, num):
for i in range(9):
if self.sudo[y][i] == num:
return False
if self.sudo[i][x] == num:
return False
yy = (y//3)*3
xx = (x//3)*3
for i in range(3):
for j in range(3):
if self.sudo[yy+i][xx+j] == num:
return False
return True
def solve(self):
for i in range(9):
for j in range(9):
if self.sudo[i][j] == 0:
for nr in range(1,10):
if Sudoku.possible(i,j,nr): #line 34
self.sudo[i][j] = nr
Sudoku.solve()
self.sudo[i][j] = 0
return
if Sudoku.solution_number > 1: #if there is more than one solution, include solution number
print("Solution Number {}".format(Sudoku.solution_number))
else: print("Solution Number 1")
print(self.sudo)
Sudoku.add_sol_num()
@classmethod
def add_sol_num(cls):
cls.solution_number += 1
运行后:
s = Sudoku(su) #where su is a numpy array sudoku
s.solve() #line 52
我得到错误:
File "/Users/georgesvanheerden/Python/Projects/Sudoku/SudokuSolver.py", line 52, in <module>
s.solve()
File "/Users/georgesvanheerden/Python/Projects/Sudoku/SudokuSolver.py", line 34, in solve
if Sudoku.possible(i,j,nr):
TypeError: possible() missing 1 required positional argument: 'num'
[Finished in 1.9s with exit code 1]
抱歉,如果代码太多,我不知道要删掉哪些部分。