0
我试图计算从某个位置满足特定位置的邻接单元格的数量,该矩阵满足特定条件(包含字符串的列表) - 每个单元格有八个相邻单元格 - 。到目前为止我已经做到了这一点,但它似乎并没有成功地工作(不通过断言数4):矩阵中的相邻单元格(字符串列表)
def calculate_adjacents(matrix,row,column):
'''Calculates the number of cells adjacent to the cell in (row,column)'''
adjacents = 0
for i in range(row-1,row+2):
for j in range(column-1,column+2):
if i == len(matrix) or j == len(matrix[i]):
break
if matrix[i][j] == "#":
adjacents += 1
return adjacents
此外,必须验证这一点:
def test_calculate_adjacents():
assert calculate_adjacents((['.']), 0, 0) == 0
assert calculate_adjacents((['..', '..']), 0, 0) == 0
assert calculate_adjacents((['..', '..']), 0, 1) == 0
assert calculate_adjacents((['##', '..']), 0, 0) == 2
assert calculate_adjacents((['##', '..']), 0, 1) == 2
assert calculate_adjacents((['#.', '.#']), 0, 0) == 4
assert calculate_adjacents((['##', '##']), 0, 0) == 8
assert calculate_adjacents((['.#.', '#.#', '.#.']), 1, 1) == 4
assert calculate_adjacents((['.#.', '..#', '.#.']), 1, 1) == 3
好像这是关系到康威生命游戏。如果“环绕”意味着我认为它的意思,那么你需要在像'row - 1'等表达式中使用模块化算术。除非你编码它,否则它不会环绕。另外 - 为什么'row + 2'而不是'row + 1'?似乎不一致。 –
欢迎来到StackOverflow。请阅读并遵守帮助文档中的发布准则。 [最小,完整,可验证的示例](http://stackoverflow.com/help/mcve)适用于此处。在发布您的MCVE代码并准确描述问题之前,我们无法为您提供有效的帮助。 *如何*这不起作用?这些测试会返回什么样的价值,您觉得它有什么问题? – Prune
是的,它与康威的生命游戏有关。我会尝试使用模块化算术表达式。它没有通过四个断言 – Facu