So I was trying to solve the N queens problem in Python, and I generated my chess board using the following statement, in my Solution class:
self.board = [[0] * self.dimension] * self.dimension
where dimension is initialized to the value that defines the number of Queens, and hence the size of the chessboard
After obtaining a list of possible positions ( a list of tuples, held in the class variable queen_positions, where each tuple holds a position on the board), I attempted to print the solution using the following:
def print_board(self):
"""
Prints the board
"""
for i, j in self.queen_positions:
self.board[i][j] = 'Q'
print(self.board)
And much to my horror, instead of updating the specific coordinates specified by the indices, it also updated additional coordinates. For instance, for position (0,1), after the update, my board looked like this:
[[0, 'Q', 0, 0], [0, 'Q', 0, 0], [0, 'Q', 0, 0], [0, 'Q', 0, 0]]
I noticed that if I did not generate the board at the beginning, but hard coded it as a 4x4 list, this does not happen.
From IDLE
board = [[0,0,0,0],[1,1,1,1], [2,2,2,2], [3,3,3,3]]
for i,j in [(1,1),(2,2)]:
print(f"i is ${i} and j is ${j}")
board[i][j] = 'Q'
>>> board
[[0, 0, 0, 0], [1, 'Q', 1, 1], [2, 2, 'Q', 2], [3, 3, 3, 3]]
What am I missing here?