How to gracefully create a matrix with the row and column indices as the first row / column?

I am having difficulty creating a matrix for a specific number of rows and columns, a matrix that contains indices as the first row or column respectively.

# At first I create list of lists with 0 at every position

string1 = "dog"
string2 = "hippo"

Dist = [[0 for column in  range(len(string1)+1)] for row in range(len(string2)+1)]

      

I would like to simplify this step if possible:

Dist[0] = [x for x in range(len(string1)+1)]

for x in range(len(string2)+1):
        Dist[x][0] = x

      

This is what the desired and current result looks like (this is a list of lists):

print(Dist)
    [[0, 1, 2, 3], 
    [1, 0, 0, 0], 
    [2, 0, 0, 0], 
    [3, 0, 0, 0], 
    [4, 0, 0, 0], 
    [5, 0, 0, 0]]

      

I am planning to use this matrix in a distance calculation problem, but this is a separate part that I don't need to tackle.

My main question is if I am doing it right (I think not) and how to do it better. Anyone, even general advice would be appreciated.

+3


source to share


3 answers


As you noted numpy

, there is an option here numpy

:



n_cols, n_rows = len(string1)+1, len(string2)+1
Dist = np.zeros((n_rows, n_cols), dtype=np.int32)

Dist[0,:] = np.arange(n_cols)
Dist[:,0] = np.arange(n_rows)
Dist
#array([[0, 1, 2, 3],
#       [1, 0, 0, 0],
#       [2, 0, 0, 0],
#       [3, 0, 0, 0],
#       [4, 0, 0, 0],
#       [5, 0, 0, 0]], dtype=int32)

      

+4


source


How to simply assign to an np.arange

array np.zero

:



>>> import numpy as np

>>> x = 6
>>> y = 4
>>> arr = np.zeros((x, y), dtype=int)
>>> arr[0, :] = np.arange(y)
>>> arr[:, 0] = np.arange(x)
>>> arr
array([[0, 1, 2, 3],
       [1, 0, 0, 0],
       [2, 0, 0, 0],
       [3, 0, 0, 0],
       [4, 0, 0, 0],
       [5, 0, 0, 0]])

      

+4


source


Since we're aiming for elegance, here's one compact version of c np.ogrid

that sets the ranges of the arrays for us and then we can assign both of those first rows and columns in one step -

L1,L2 = len(string1)+1, len(string2)+1
Dist1 = np.zeros((L2,L1),dtype=int)
Dist1[:,[0]], Dist1[0] = np.ogrid[:L2,:L1]

      

Sample output -

In [76]: Dist1
Out[76]: 
array([[0, 1, 2, 3],
       [1, 0, 0, 0],
       [2, 0, 0, 0],
       [3, 0, 0, 0],
       [4, 0, 0, 0],
       [5, 0, 0, 0]])

      

+3


source







All Articles