I want to represent sparse matrix in Python in a data structure that does not waste space but in the same time preserves constant access time. Is there any easy/trivial way of doing it? I know that libraries such as scipy have it.
3 Answers
The scipy.sparse library uses different formats depending on the purpose. All implement a 2d matrix
dictionary of keys - the data structure is a dictionary, with a tuple of the coordinates as key. This is easiest to setup and use.
list of lists - has 2 lists of lists. One list has column coordinates, the other column data. One sublist per row of matrix.
coo - a classic design. 3 arrays, row coordinates, column coordinates and data values
compressed row (or column) - a more complex version of
coo, optimized for mathematical operations; based on linear algebra mathematics decades olddiagonal - suitable for matrices were most values are on a few diagonals