Print Checkerboard Pattern of NxN using NumPy in Python

Make a checkerboard in NumPy: In this tutorial, we will learn how to print the checkerboard pattern of nxn using NumPy in Python? By Pranit Sharma Last updated : May 29, 2023

Suppose that we are given a pixel array and we need to create a checkerboard i.e., ndarray with white and black squares (0 and 1 pixels) at alternate position

How to Print Checkerboard Pattern of NxN using NumPy?

To print checkerboard pattern of NxN using NumPy, create a NumPy matrix with N*N elements by filling it with 0 and 1. You can define a function in which create a matrix with the 0s and 1s and construct the matrix using the numpy.row_stack() method to make the checkboard pattern.

Let us understand with the help of an example,

Python Program to Print Checkerboard Pattern of NxN using NumPy

# Import numpy
import numpy as np

# Creating a function
def fun(white,black):
    re = np.r_[ white*[0,1] ]
    ro = np.r_[ white*[1,0] ]
    return np.row_stack(black*(re, ro))

# Creating a checkerboard
checkerboard = fun(5, 5)

# Display result
print("Checkboard Pattern:\n",checkerboard,"\n")

Output

Checkboard Pattern:
 [[0 1 0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0 1 0]]

Output (Screenshot)

Print Checkerboard Pattern of NxN | Output

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.