Advanced OOP and patterns · 13 / 15 Exercise Hard

Sparse matrix with magic methods

Objective

The special methods __getitem__, __setitem__, __len__, __contains__ and __iter__ make your class behave like a native container: m[i, j], len(m), (i, j) in m and for ... in m.

Instructions

  • Create SparseMatrix that stores only the non-zero values in a dictionary: reading an empty position gives 0, assigning 0 removes the position, len counts the occupied positions and iter walks them in order.
  • The first line has the number n of commands: set i j v, get i j (shows the value), has i j (shows True or False), count (shows the amount) or dump (shows i j v for each occupied position, sorted).
Input
5
set 0 1 5
set 2 2 7
get 0 1
get 1 1
count
Output
5
0
2

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise