This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 8: NumPy recap and exercises

Checkerboard pattern

face Joe Stacey Josiah Wang

A final mega-challenge question!

Challenge #5

Using as few lines of code as possible, create an 8 \times 8 NumPy array with a checkerboard pattern:

[
 [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],
 [1, 0, 1, 0, 1, 0, 1, 0]
]

There are potentially many solutions to this! You can even try generalising the board to N \times N for any N if you are up for it!

There are many solutions for these question!

Here is one that uses list comprehension to create different 2D off-diagonal arrays and then adds them all up.

n = 8
checkerboard = np.sum(np.dstack([
                        np.eye(n, k=k, dtype=int) 
                        for k in np.arange(-(n+1), n+1, 2)]
                ), axis=2)

Here is another clever one. It uses np.indices to obtain the (row, col) indices for a grid, and then adds up the indices of each row+col. If the row+col is even, then it should display 0 (e.g. (0,0), (0,2)). Otherwise, display 1.

n = 8
checkerboard = np.indices((n, n)).sum(axis=0) % 2

The next solution uses np.tile() to tile up [[0 1],[1 0]]. It only works for an even number of rows/cols though!

np.array(np.tile(np.eye(2) == 0, (4, 4)), dtype=int)

This following solution uses just pure Python (except for creating the np.array). It also only works for an even number of rows/cols!

x = np.array([[0, 1] * 4, [1, 0] * 4] * 4)

This stackoverflow page has even more solutions! Choose your favourite!