Creating a Checkerboard Matrix

Write a NumPy program to create an 8×8 matrix and fill it with a checkerboard pattern. Return the matrix.

Example 1:

Input: None 

Output: array([[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]])

Example 2:

Input: None 

Output: array([[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]])

You can start by creating a matrix of zeros and then fill alternate cells with 1s to create a checkerboard pattern.

import numpy as np

def create_checkerboard():
    matrix = np.zeros((8,8),dtype=int)
    matrix[1::2,::2] = 1
    matrix[::2,1::2] = 1
    return matrix

print(create_checkerboard())

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!