for r in range(max(row-1,0), min(row+2,numrows))The rest of this should be fairly obvious.

Python

<pre> def printGrid(grid): """Prints out the minsweeper grid""" for row in grid: out = '' for col in row: out += f'{col:^3}' print(out) def numAdjacent(grid: list, row: int, col: int) -> int: """Returns the number of mines '#' adjacent to the given cell""" numrows,numcols = len(grid), len(grid[0]) nummines = 0 #Use range to generate a range of rows and columns from #one less than the given row and column to one more. for r in range(max(row-1,0), min(row+2,numrows)): for c in range(max(col-1,0), min(col+2,numcols)): nummines += grid[r][c] == '#' return nummines def mineSweeper(grid: list) -> list: """ Takes a grid (a list of lists of equal length) where each element is either '-' (no mine) or '#' (mine) and returns a grid where each '-' in the original grid is replaced by a number indicating the number of mines in adjacent cells. """ #determine rows and column sizes numrows = len(grid) numcols = len(grid[0]) #make new grid with '-' replaced by the number of adjacent mines newgrid = grid for row in range(0, numrows): for col in range(0, numcols): if newgrid[row][col] == '-': newgrid[row][col] = numAdjacent(grid,row,col) return newgrid grid = [ ["-", "-", "-", "#", "#"], ["-", "#", "-", "-", "-"], ["-", "-", "#", "-", "-"], ["-", "#", "#", "-", "-"], ["-", "-", "-", "-", "-"], ] printGrid(grid) print('') printGrid(mineSweeper(grid))