A Dictionary-of-Keys Sparse Matrix

medium
Unit 17 · Data Structures & Recursion0/3 to milestone

Most entries in a user × item matrix are zero, so store only the non-zeros. Implement a class SparseMatrix(rows, cols) that keeps a dict from (i, j) to value:

  • m[i, j] reads (0 when absent) and m[i, j] = v writes. Writing 0 removes the entry. Out-of-range indices raise IndexError.
  • nnz (the number of stored entries), from_dense(list_of_lists) (a classmethod) and to_dense()
  • transpose()
  • m + other: element-wise, shapes must match (ValueError otherwise), with zero results not stored
  • m @ other: matrix multiplication that only visits non-zeros. Group other's entries by row first, so each non-zero (i, k) of m meets only the entries (k, j) of other.
#data-structures#linear-algebra#dunder-methods2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
A Dictionary-of-Keys Sparse Matrix · TechGradify