Generate fenced Matrix with m and n integers

Viewed 444

How to generate a matrix with border 1's and 0's at the core when we give m and n positive integers.

Input:
4,5


Output
    [1, 1, 1, 1, 1]
    [1, 0, 0, 0, 1]
    [1, 0, 0, 0, 1]
    [1, 1, 1, 1, 1]

I used this code.Is there any other way to get the output

import numpy as np
a=np.ones((m,n),dtype="int")
a[1:-1,1:-1]=0
2 Answers

Another similar solution, however I prefer the suggested solution in the question:

a=np.zeros((m,n),dtype="int")
a[[0,-1]] = 1
a[:,[0,-1]] = 1

Or per @Paul's suggestion in comments:

a[::m-1] = a[:,::n-1] = 1

EDIT: Per OP's comment below:

list of arrays:

 a = [x for x in a]

array of lists:

b = np.empty(m,dtype=object)
b[:] = a.tolist()
in_str=input()
in_str=in_str.split(',')
m=int(in_str[0])
n=int(in_str[1])

#make a list with n zeroes
final=[0]*n

#make a matrix of m such lists
final=[list(final) for i in range(m)]
for i in range(m):
    for j in range(n):
        if i==0 or j==0 or i==m-1 or j==n-1:
            final[i][j]=1
            
#print in the fashion as shown in Sample output
for i in final:
    print(i)
Related