I'm relatively new in programming with Python. This code was working perfectly, until I tried turning it into a class. I'm making a class for my sudoku solver code, to practice classes and dabbling my toes in object oriented programming.
So I have read a whole bunch of questions from users who have a similar problem, most answers were : -instantiate class first before calling a function from said class but none of them seem to work for my specific example.
Here is my class:
#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
After running:
s = Sudoku(su) #where su is a numpy array sudoku
s.solve() #line 52
I get the error:
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]
Sorry if this is too much code, I didn't know which parts to cut out.
self
usingself.possible
, notSudoku.possible
. You are doing similar things multiple times.