Creating a Border

Write a NumPy program to create a 2d array with 1 on the border and 0 inside. Return the 2d array.

Example 1:

Input: None 

Output: array([[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]])

Example 2:

Input: None 

Output: array([[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]])

You can create a 2d array filled with 1s using np.ones(). Then, you can set the inner part of the array to 0.

import numpy as np

def create_border():
    array = np.ones((4,5))
    array[1:-1,1:-1] = 0
    return array

print(create_border())

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!