|
Data Structures and Algorithms
with Object-Oriented Design Patterns in Python |
The simplest way to implement a matrix is to use a multi-dimensional
array with two dimensions as shown in Program
.
The DenseMatrix class extends the Matrix class
discussed in the preceding section.
The DenseMatrix class adds a instance attribute called _array
which is a multi-dimensional array.
The __init__ method of the DenseMatrix class takes two arguments,
and
,
and constructs the corresponding
multi-dimensional array.
Clearly, the running time of the __init__ method is O(mn).

Program: DenseMatrix class __init__, __getitem__ and __setitem__ methods.
Program
also defines the __getitem__ and setitem
methods for the DenseMatrix class.
These methods each take an ordered pair, (i,j),
as the index expression and use the pair
as the index into the multi-dimensional array.
Because the number of dimensions is fixed at two,
the running time for each of these methods is O(1).