Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

python - increasing values in numpy array inside out

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.]]
question from:https://stackoverflow.com/questions/65886475/increasing-values-in-numpy-array-inside-out

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...