矩阵中的相邻单元格(字符串列表)

时间:2017-04-14 00:31:17

标签: python python-3.x

我正在尝试计算某个位置的相邻单元格的数量,这些单元格符合环绕矩阵中的某个条件(带有字符串的列表) - 每个单元格有八个相邻的单元格。。到目前为止,我已经完成了这个但是它似乎没有成功工作(它没有通过断言号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

1 个答案:

答案 0 :(得分:0)

你有一个小问题,在康威的“生命”游戏中很常见:你也在计算中心广场。如果中心方块处于活动状态,则将计数设置为-1:

if matrix[row][column] == "#":
    adjacents = -1
else:
    adjacents = 0

或者,对于单行:

adjacents = -1 if matrix[row][column] == "#" else 0