|
Data Structures and Algorithms
with Object-Oriented Design Patterns in Python |
The elements of a multi-dimensional array are accessed
using the __getitem__ and __setitem__ methods
of the MultiDimensionalArray class.
For example,
you can access the
element
of a three-dimensional array a like this:
value = a[i,j,k]which invokes the __getitem__ method with the tuple (i,j,k) as the index expression. Similarly, you can modify the
a[i,j,k] = valuewhich invokes the setitem method with the tuple (i,j,k) as the index expression.
Program
shows how
that __getitem__ and __setitem__ methods
are both implemented using a getOffset method.
The getOffset method takes a tuple of n indices
and computes the position of the corresponding element
in the one-dimensional array according to Equation
.
This computation takes O(n) time in the worst case,
where n is the number of dimensions.
Consequently, the running times of the get and set
accessors are also O(n).

Program: MultiDimensionalArray class __getitem__ and __setitem__ methods.