I am fairly new to python, and I am trying to design a class to solve the N Queen Problem. This is my class def:
class QueenSolver:
def genEmptyBoard(self, n):
# Generates an empty board of n width and n height
board = []
for _ in range(n):
board.append([0 for _ in range(n)])
return board
def genLegalBoard(self, q1, q2, n):
# Returns legal board or false
board = self.genEmptyBoard(self, n)
try:
board[q1[0]][q1[1]] = 'q'
except IndexError:
print("Queen placed outside of board constraints")
return False
try:
if board[q2[0]][q2[1]] == 'q':
print("Queens cannot be placed in the same position")
return False
board[q2[0]][q2[1]] = 'Q'
except IndexError:
print("Queen placed outside of board constraints")
return False
return board
However, when I call this method outside of the class, like this:
board = QueenSolver.genLegalBoard([0, 0], [7, 7], 8)
I get an error that looks like this:
Exception has occurred: TypeError
QueenSolver.genLegalBoard() missing 1 required positional argument: 'n'
Apparently I have to supply the "self" variable when calling it from outside the class definition? I thought the "self" parameter doesn't require any value, because it is assumed? What am I missing here?
CodePudding user response:
You need to Instantiate an object of QueenSolver
class before calling the method of the class. As well as, remove self
from board = self.genEmptyBoard(self, n)
.
class QueenSolver:
def genEmptyBoard(self, n):
# Generates an empty board of n width and n height
board = []
for _ in range(n):
board.append([0 for _ in range(n)])
return board
def genLegalBoard(self, q1, q2, n):
# Returns legal board or false
board = self.genEmptyBoard(n)
try:
board[q1[0]][q1[1]] = 'q'
except IndexError:
print("Queen placed outside of board constraints")
return False
try:
if board[q2[0]][q2[1]] == 'q':
print("Queens cannot be placed in the same position")
return False
board[q2[0]][q2[1]] = 'Q'
except IndexError:
print("Queen placed outside of board constraints")
return False
return board
QS = QueenSolver()
board = QS.genLegalBoard([0, 0], [7, 7], 8)
Output:
[['q', 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 'Q']]