I need to make a checkerboard using only 1 and 0's by using lists to make a grid. I have created a code that creates an 8 by 8 grid of 0's. Then I attempt to use a nested for loop to fill it in, what am I doing wrong?
board = []
def print_board(board):
for i in range(8):
board.append([0]*8)
for i in range(len(board)):
for j in range(len(board[i])):
if i == 0 or i == 2 or i == 4 or i == 6 and j == 1 or j == 3 or j==5 or j==7:
board[i][j] = 1
elif i == 1 or i ==3 or i == 5 or i == 7 and j == 0 or j == 2 or j==4 or j==6:
board[i][j] = 1
for i in range(len(board)):
print(board[i])
print_board(board)
Why are the if and elif statements not working?
CodePudding user response:
To make a checkerboard, a simple strategy is to check the parity of rows/cols.
If identical, set to 1 (or 0), if different, set the other way around.
This can be achieved with a simple list comprehension:
def board(n=8):
return [[int(i%2==j%2) for i in range(n)] # converting True to 1 directly
for j in range(n)]
output:
board(8)
[[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1]]
board(5)
[[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1]]
CodePudding user response:
The reason that the code doesn't work is that the interpreter treats:
i == 0 or i == 2 or i == 4 or i == 6 and j == 1 or j == 3 or j==5 or j==7:
as
((i == 0 or i == 2 or i == 4 or i == 6) and j == 1) or j == 3 or j==5 or j==7:
i.e. it starts from the left and evaluates each operator one by one. You can correct your code by replacing:
if i == 0 or i == 2 or i == 4 or i == 6 and j == 1 or j == 3 or j==5 or j==7:
board[i][j] = 1
elif i == 1 or i ==3 or i == 5 or i == 7 and j == 0 or j == 2 or j==4 or j==6:
board[i][j] = 1
With:
if (i == 0 or i == 2 or i == 4 or i == 6) and (j == 1 or j == 3 or j==5 or j==7):
board[i][j] = 1
elif (i == 1 or i ==3 or i == 5 or i == 7) and (j == 0 or j == 2 or j==4 or j==6):
board[i][j] = 1
Or replace it with this condition
if i % 2 == 0 and j % 2 != 0:
board[i][j] = 1
elif i % 2 != 0 and j % 2 == 0:
board[i][j] = 1
A better way to do this would be:
board = []
for i in range(0, 8):
board.append([])
for j in range(0, 8):
board[i].append((i j) % 2)
print(board[-1])
Or
def board(k=8):
return [[int(i%2!=j%2) for i in range(k)] for j in range(k)]