简体   繁体   中英

How do you make a checkerboard?

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?

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]]

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:

ie 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)] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM