1
\$\begingroup\$

Assessment Question: Print an array of size n*n, with border as 1's and rest of the element as 0's.

Sample Input: 5

Sample Output:

[[1 1 1 1 1]
 [1 0 0 0 1]
 [1 0 0 0 1]
 [1 0 0 0 1]
 [1 1 1 1 1]]

Here is my solution:

import numpy as np
n = int(input("Enter a number:"))
np_box = np.zeros([n, n], dtype='int')
np_box[:, 0] = np_box[:, -1] = np_box[0] = np_box[-1] = 1
print(np_box)  

Can this code be still optimised (using numpy, considering space and time complexity)?

\$\endgroup\$
1
  • \$\begingroup\$ Because printing is involved, the problem cannot be large scale. And you've delegated the work to numpy. In light of those things, why is memory/speed optimization an issue here at all? \$\endgroup\$
    – FMc
    Aug 31, 2020 at 0:05

1 Answer 1

1
\$\begingroup\$

Have you alread checked out np.pad?

import numpy as np
n = int(input("Enter a number:"))
np_box = np.pad(np.zeros((n-1,n-1)), 1, constant_values=1)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.