w3resource

NumPy: Create a 8x8 matrix and fill it with a checkerboard pattern

NumPy: Array Object Exercise-10 with Solution

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

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 3x3 NumPy array filled with ones
x = np.ones((3, 3))

# Printing a message indicating the checkerboard pattern
print("Checkerboard pattern:")

# Creating an 8x8 NumPy array filled with zeros and setting alternate elements to 1 to create a checkerboard pattern
x = np.zeros((8, 8), dtype=int)
x[1::2, ::2] = 1  # Setting alternate rows starting from the second row with alternate columns to 1
x[::2, 1::2] = 1  # Setting alternate rows starting from the first row with alternate columns to 1

# Printing the resulting checkerboard pattern array
print(x) 

Sample Output:

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

Explanation:

In the above code –

x = np.ones((3,3)): Creates a 3x3 NumPy array filled with ones. However, this line is not relevant to the final output and can be ignored.

x = np.zeros((8,8),dtype=int): Creates an 8x8 NumPy array filled with zeros, with an integer data type.

x[1::2,::2] = 1: Assigns the value 1 to every other element in every other row, starting from the second row (index 1).

x[::2,1::2] = 1: Assigns the value 1 to every other element in every other column, starting from the second column (index 1).

print(x): Prints the 8x8 NumPy array.

Python-Numpy Code Editor:

Previous: Write a NumPy program to add a border (filled with 0's) around an existing array.
Next: Write a NumPy program to convert a list and tuple into arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-10.php