Data Structures and Algorithms using Python
Copyright © 2023 by Rance Necaise
Table Of Contents
Data Structures and Algorithms using Python
Copyright © 2023
by Rance Necaise

4.1 Two-Dimensional Arrays

Some problems require the use of a two-dimensional array, which organizes data into rows and columns similar to a table or grid. The individual elements are accessed by specifying two indices, one for the row and one for the column, [i,j]. Figure 4.1.1 shows an abstract view of both a one- and a two-dimensional array.

Figure 4.1.1: Sample arrays: (left) a 1-D array viewed as a sequential list and (right) a 2-D array viewed as a rectangular table or grid.

As we saw earlier, Python does not directly support built-in arrays of any dimension. But, in the previous chapter, we used the EzArrays module to create and work with one-dimensional hardware-supported arrays. Two-dimensional arrays are also very common in computer programming, where they are used to solve problems that require data to be organized into rows and columns. Since 2-D arrays are not provided by Python, we define the Array2D abstract data type for creating 2-D arrays. It consists of a limited set of operations similar to those provided by the one-dimensional Array ADT from the previous chapter.

The Array2D ADT

A two-dimensional array consists of a collection of elements organized into rows and columns. Individual elements are referenced by specifying the specific row and column indices (r,c), both of which start at 0.

  • Array2D(nrows, ncols)

    Creates a two-dimensional array organized into rows and columns. The nrows and ncols arguments indicate the size of the table, both of which must be greater than 0. The individual elements of the table are initialized to None.

  • numRows()

    Returns the number of rows in the 2-D array.

  • numCols()

    Returns the number of columns in the 2-D array.

  • clear(value)

    Clears the array by setting each element to the given value.

  • getitem(index1, index2)

    Returns the value stored in the 2-D array element at the position indicated by the 2-tuple (index1, index2), both of which must be within the valid range. Accessed using the subscript operator: y = x[1,2].

  • setitem(index1, index2, value)

    Modifies the contents of the 2-D array element indicated by the 2-tuple (index1, index2) with the new value. Both indices must be within the valid range. Accessed using the subscript operator: x[0,3] = y.

Page last modified on August 24, 2023, at 02:22 PM