Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build 2d pyramidal array - Python / NumPy

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!

like image 851
hdc94 Avatar asked Apr 12 '19 08:04

hdc94


2 Answers

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]])
like image 126
Divakar Avatar answered Nov 07 '22 13:11

Divakar


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.

like image 26
Chris Avatar answered Nov 07 '22 12:11

Chris