2025-09-17
Grid here must recognize two methods that return the number of rows and the number of columns:getHeight and getWidth Techniques for manipulating one-dimensional arrays are easily extended to gridsfrom arrays import Array
class Grid(object):
"""Represents a two-dimensional array."""
def __init__(self, rows, columns, fillValue = None):
self.data = Array(rows) # recall that we previously defined the Array class which is imported
for row in range (rows):
self.data[row] = Array(columns, fillValue)
def getHeight(self):
"""Returns the number of rows."""
return len(self.data)
def getWidth(self):
"Returns the number of columns."""
return len(self.data[0])
def __getitem__(self, index):
"""Supports two-dimensional indexing
with [row][column]."""
return self.data[index]
def __str__(self):
"""Returns a string representation of the grid."""
result = ""
for row in range (self.getHeight()):
for col in range (self.getWidth()):
result += str(self.data[row][col]) + " "
result += "\n"
return result-The following code segment traverses the grid to reset its cells to the values shown in next slide:
Grid constructor with three arguments: height = 4, width = 5, and an initial fill value = 0:from grid import Grid
grid = Grid(4, 5, 0)
print(grid)
# >>> Output
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0