Build 2d pyramidal array - Python / NumPy
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.