
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to print a checkboard pattern of n*n using numpy.
The checkboard pattern is the square grid composed of alternating 0s and 1s, arranged in a way that no two adjacent cells have the same value. It looks like the chessboard, where black and white squares alternate in every row and column.
This kind of pattern is not only seen in chess or checkers, but also in image processing, graphics, and visualization, etc. In this article, we are going to learn how to print a checkboard pattern of n*n using numpy.
Using Python numpy.indices() Method
The numpy.indices() method is used to return the grid of indices with the given shape. It creates the coordinate matrices from coordinate vectors.
Syntax
Following is the syntax of Python numpy.indices() method -
numpy.indices(dimensions, dtype=int)
Example 1
Let's look at the following example, where we are going to print a checkboard of 2*2 pattern.
import numpy as np def demo(n): result = (np.indices((n, n)).sum(axis=0)) % 2 print(result) demo(2)
The output of the above program is as follows -
[[0 1] [1 0]]
Example 2
In the following example, we are going to use the 4*4 to print a checkboard pattern.
import numpy as np def demo(n): result = (np.indices((n, n)).sum(axis=0)) % 2 print(result) demo(4)
The following is the output of the above program -
[[0 1 0 1] [1 0 1 0] [0 1 0 1] [1 0 1 0]]