Matrix data structure

A simple 2-dimensional array allows exchanging rows (or columns) in a matrix O (1) times. Is there an effective data structure that would allow exchanging both rows and columns of the matrix O (1) times?

+3
source share
2 answers

You must save your matrix as either a list of rows or a list of columns. This gives either a row replacement or a column replacement in O (1).

However, you can add another layer on top of it to handle the column order so that you can reorder the columns in O (1).

So, for each access you need:

x = data[row][colorder[col]] 

Swap as:

data[row1], data[row2] = data[row2], data[row1]

And replace the columns as:

colorder[col1], colorder[col2] = colorder[c2], colorder[c1]
+4
source

, numpy - ( SciPy)

>>> def f(x,y):
...         return 10*x+y
...
>>> b = fromfunction(f,(5,4),dtype=int)
>>> b
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])
>>> b[:,1]                                 # the second column of b
array([ 1, 11, 21, 31, 41])
>>> b[1:3,:]                               # the second and third row of b
array([[10, 11, 12, 13],
       [20, 21, 22, 23]])
0

Source: https://habr.com/ru/post/1722083/


All Articles