I've been boggling my head to make this array for some time but having no success doing it in a vectorized way.
I need a function that takes in the 2d array size n and produces a 2d array of size (n, n) looking like this:
n = 6
np.array([[0,0,0,0,0,0],
[0,1,1,1,1,0],
[0,1,2,2,1,0],
[0,1,2,2,1,0],
[0,1,1,1,1,0],
[0,0,0,0,0,0],
(and can take odd number arguments)
Any suggestions would be much appreciated, thanks!
Approach #1
We can use broadcasting
-
def pyramid(n):
r = np.arange(n)
d = np.minimum(r,r[::-1])
return np.minimum.outer(d,d)
Approach #2
We can also use concatenation
to create d
, like so -
d = np.r_[np.arange(n//2),np.arange(n//2-(n%2==0),-1,-1)]
Thus, giving us an alternative one-liner -
np.minimum.outer(*(2*[np.r_[np.arange(n//2),np.arange(n//2-(n%2==0),-1,-1)]]))
Sample runs -
In [83]: pyramid(5)
Out[83]:
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 2, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]])
In [84]: pyramid(6)
Out[84]:
array([[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 1, 2, 2, 1, 0],
[0, 1, 2, 2, 1, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]])
In [85]: pyramid(8)
Out[85]:
array([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 2, 2, 2, 2, 1, 0],
[0, 1, 2, 3, 3, 2, 1, 0],
[0, 1, 2, 3, 3, 2, 1, 0],
[0, 1, 2, 2, 2, 2, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0]])
Use numpy.pad
:
import numpy as np
def pyramid(n):
if n % 2:
arr = np.zeros((1,1))
N = int((n-1)/2)
else:
arr = np.zeros((2,2))
N = int(n/2)-1
for i in range(N):
arr += 1
arr = np.pad(arr, 1, mode='constant')
return arr
Output:
pyramid(6)
array([[0., 0., 0., 0., 0., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 1., 2., 2., 1., 0.],
[0., 1., 2., 2., 1., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 0., 0., 0., 0., 0.]])
pyramid(5)
array([[0., 0., 0., 0., 0.],
[0., 1., 1., 1., 0.],
[0., 1., 2., 1., 0.],
[0., 1., 1., 1., 0.],
[0., 0., 0., 0., 0.]])
numpy.pad(arr, 1, 'constant')
returns arr
wrapped with 1 layer of zeros.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With