我必须创建一个函数来计算网格中给定单元格周围的所有邻居。不仅如此,它还必须返回所有等于 1 的“活邻居”,而不返回中间单元格的值。我一直在阅读论坛,试图准确理解我将如何做到这一点,但我仍然很困惑。
这是迄今为止我的代码以及老师给我的说明:
def countLiveNeighbors( grid, rowIndex, columnIndex ):
# TODO - Find the number of grid rows (HINT: use the len() of the grid)
rows = len(grid)
# TODO - Find the number of grid columns (HINT: use the len() of the first row)
cols = len(grid[0])
# TODO - Compute neighbor indices.
# Make sure all indices are positive!
# Make sure all indices are not too large!
r = rowIndex
c = columnIndex
for row in rows:
for col in cols:
if col >= 0:
grid[r][c] + 1
else:
grid[r][c] - 1
# TODO - Count the number of live neighbors.
# Do NOT count the cell in the middle, only neighbors!
# TODO - Return the number of live neighbors
# make a test grid to test you function on
testGrid = [[0,0,0,0,0],
[0,1,1,0,0],
[0,1,1,0,0],
[0,0,0,0,0]]
# count the live neighbors for a cell at some row and column
row = 1
col = 2
neighborCount = life_module.countLiveNeighbors( testGrid, row, col )
print( "cell at row", row, "and col", col, "has", neighborCount, "live neighbors" )
我不明白我会采取什么步骤来找到邻居并只计算存活的邻居。如果有人可以解释它是如何完成的并纠正我的代码,我将非常感激。
给定一些单元格
grid[r][c]
,对应于上、下、左、右邻居的位置是grid[r - 1][c]
、grid[r + 1][c]
、grid[r][c - 1]
和grid[r][c + 1]
。如果需要对角邻居,那么应该很容易根据 4 个方向找出它们的索引。显然,您必须检查索引是否在数组的范围内,这可以通过 r in range(rows) and c in range(cols)
来完成。
执行此操作的代码如下所示:
def countLiveNeighbors( grid, rowIndex, columnIndex):
rows = len(grid)
cols = len(grid[0])
r, c = rowIndex, columnIndex
live_count = 0
#Coordinates corresponding to up, down, left, right
dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for x, y in dirs:
new_r, new_c = r + x, c + y
if new_r in range(rows) and new_c in range(cols) and grid[new_r][new_c] == 1:
live_count += 1
return live_count
# make a test grid to test you function on
testGrid = [[0,0,0,0,0],
[0,1,1,0,0],
[0,1,1,0,0],
[0,0,0,0,0]]
# count the live neighbors for a cell at some row and column
row = 1
col = 2
neighborCount = life_module.countLiveNeighbors( testGrid, row, col )
print( "cell at row", row, "and col", col, "has", neighborCount, "live neighbors" )