2

I have a question about increasing a value by 1 from the center. Write a function border(x) that takes a positive odd integer x as input, and returns an array of floats y of shape(x,x) that has the following properties:

the centre of the generated array y is 0 with each subsequent border, the number of that border increases the expected output are below for example:

border(3)
[ [1. 1. 1.],
   [1. 0. 1.],
   [1. 1. 1.] ]

border(5)
[ [ 2.  2.  2.  2.  2.]
   [ 2.  1.  1.  1.  2.]
   [ 2.  1.  0.  1.  2.]
   [ 2.  1.  1.  1.  2.]
   [ 2.  2.  2.  2.  2.] ]

I have come up with this part and don't have any more ideas to increase the value along the border. pls help me.

x = 5
a = numpy.ones((x,x))
c = x//2
a[c,c]=0

print(a)
[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 0. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]

2 Answers 2

1

You can iterate through the array and consider how far away from the center each element is, taking the maximum over both dimensions. For example, if the element is within one row and one column of the center, then there should be a 1 in that position, but if it's within one row and two columns of the center, then there should be a 2 in that position, and so on. Here's an example:

import numpy as np

def border(x):
    arr = np.zeros((x, x))
    center = x // 2
    for i in range(x):
        for j in range(x):
            arr[i, j] = max(abs(center - i), abs(center - j))

    return arr

Example output:

>>> border(5)
array([[2., 2., 2., 2., 2.],
       [2., 1., 1., 1., 2.],
       [2., 1., 0., 1., 2.],
       [2., 1., 1., 1., 2.],
       [2., 2., 2., 2., 2.]])
>>> border(7)
array([[3., 3., 3., 3., 3., 3., 3.],
       [3., 2., 2., 2., 2., 2., 3.],
       [3., 2., 1., 1., 1., 2., 3.],
       [3., 2., 1., 0., 1., 2., 3.],
       [3., 2., 1., 1., 1., 2., 3.],
       [3., 2., 2., 2., 2., 2., 3.],
       [3., 3., 3., 3., 3., 3., 3.]])
Sign up to request clarification or add additional context in comments.

Comments

0

Using numpy.pad:

import numpy as np

def border(x):
    N=int(x/2)
    y=np.pad(np.array([[0]]), (N, N), 'linear_ramp',end_values=(N,N)).astype(float) 

    return(y)

print(border(3))
print(border(5))

output:

[[1. 1. 1.]
 [1. 0. 1.]
 [1. 1. 1.]]
[[2. 2. 2. 2. 2.]
 [2. 1. 1. 1. 2.]
 [2. 1. 0. 1. 2.]
 [2. 1. 1. 1. 2.]
 [2. 2. 2. 2. 2.]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.