def neighbors(matrix, r, c):
live_neighbors = 0
if matrix[r][c-1] != 0:
live_neighbors += 1
if matrix[r-1][c] != 0:
live_neighbors += 1
if matrix[r-1][c+1] != 0:
live_neighbors += 1
if matrix[r][c-1] != 0:
live_neighbors += 1
if matrix[r][c+1] != 0:
live_neighbors += 1
if matrix[r+1][c-1] != 0:
live_neighbors += 1
if matrix[r+1][c] != 0:
live_neighbors += 1
if matrix[r+1][c+1] != 0:
live_neighbors += 1
return live_neighbors
这是我到目前为止编写的代码。如何计算边界单元的邻居?如果使用此代码,我将得到索引超出范围的错误。
答案 0 :(得分:1)
您可以使用助手功能检查边界:
def neighbors(matrix, r, c):
def get(r, c):
return 0 <= r < len(matrix) and 0 <= c < len(matrix[r]) and matrix[r][c]
live_neighbors = 0
if get(r, c-1) != 0:
live_neighbors += 1
if get(r-1, c) != 0:
live_neighbors += 1
if get(r-1, c+1) != 0:
live_neighbors += 1
if get(r, c-1) != 0:
live_neighbors += 1
if get(r, c+1) != 0:
live_neighbors += 1
if get(r+1, c-1) != 0:
live_neighbors += 1
if get(r+1, c) != 0:
live_neighbors += 1
if get(r+1, c+1) != 0:
live_neighbors += 1
return live_neighbors
您还可以在itertools.product
的生成器表达式中使用sum
而不是if
语句来计算所有活动邻居:
from itertools import product
def neighbors(matrix, r, c):
def get(r, c):
return 0 <= r < len(matrix) and 0 <= c < len(matrix[r]) and matrix[r][c]
return sum(get(r + i, c + j) for i, j in product(range(-1, 2), 2) if i or j)
答案 1 :(得分:1)
没有所有这些if
语句的可能解决方案:
def neighbors(matrix, r, c):
def get(r, c):
if 0 <= r < len(matrix) and 0 <= c < len(matrix[r]):
return matrix[r][c]
else:
return 0
neighbors_list = [get(r-1, c-1), get(r-1, c), get(r-1, c+1),
get(r , c-1), get(r , c+1),
get(r+1, c-1), get(r+1, c), get(r+1, c+1)]
return sum(map(bool, neighbors_list))
matrix = [ [0, 0, 0, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 1],
[0, 0, 1, 1, 1] ]
print(neighbors(matrix, 0, 0)) # 0
print(neighbors(matrix, 1, 2)) # 1
print(neighbors(matrix, 3, 2)) # 4
print(neighbors(matrix, 4, 4)) # 3
如果单元格的值只有0或1,则neighbors
函数将简单地返回sum(neighbors_list)
。
答案 2 :(得分:0)
最接近您的情况:
def neighbors(matrix, r, c):
live_neighbors = 0
if c and matrix[r][c-1] != 0:
live_neighbors += 1
if r and matrix[r-1][c] != 0:
live_neighbors += 1
if r and matrix[r-1][c+1] != 0:
live_neighbors += 1
if c and matrix[r][c-1] != 0:
live_neighbors += 1
if c < len(matrix[r])-1 and matrix[r][c+1] != 0:
live_neighbors += 1
if r < len(matrix)-1 and matrix[r+1][c-1] != 0:
live_neighbors += 1
if r < len(matrix)-1 and matrix[r+1][c] != 0:
live_neighbors += 1
if r < len(matrix)-1 and matrix[r+1][c+1] != 0:
live_neighbors += 1
return live_neighbors
等等。