|
1
|
|
|
def count_neighbours(grid, row, col): |
|
2
|
|
|
# get indexes of rows and cols we want to slide out |
|
3
|
|
|
rows = [i for i in range(row - 1, row + 2) if 0 <= i <= len(grid) - 1] |
|
4
|
|
|
cols = [i for i in range(col - 1, col + 2) if 0 <= i <= len(grid[0]) - 1] |
|
5
|
|
|
neighbors = [grid[r][c] for r in rows for c in cols] |
|
6
|
|
|
# we don't want to count outselves |
|
7
|
|
|
return sum(neighbors) - grid[row][col] |
|
8
|
|
|
|
|
9
|
|
|
|
|
10
|
|
|
if __name__ == '__main__': # pragma: no cover |
|
11
|
|
|
# These "asserts" using only for self-checking and not necessary for |
|
12
|
|
|
# auto-testing |
|
13
|
|
|
assert count_neighbours( |
|
14
|
|
|
((1, 0, 0, 1, 0), |
|
15
|
|
|
(0, 1, 0, 0, 0), |
|
16
|
|
|
(0, 0, 1, 0, 1), |
|
17
|
|
|
(1, 0, 0, 0, 0), |
|
18
|
|
|
(0, 0, 1, 0, 0),), 1, 2) == 3, "1st example" |
|
19
|
|
|
assert count_neighbours(((1, 0, 0, 1, 0), |
|
20
|
|
|
(0, 1, 0, 0, 0), |
|
21
|
|
|
(0, 0, 1, 0, 1), |
|
22
|
|
|
(1, 0, 0, 0, 0), |
|
23
|
|
|
(0, 0, 1, 0, 0),), 0, 0) == 1, "2nd example" |
|
24
|
|
|
assert count_neighbours(((1, 1, 1), |
|
25
|
|
|
(1, 1, 1), |
|
26
|
|
|
(1, 1, 1),), 0, 2) == 3, "Dense corner" |
|
27
|
|
|
assert count_neighbours(((0, 0, 0), |
|
28
|
|
|
(0, 1, 0), |
|
29
|
|
|
(0, 0, 0),), 1, 1) == 0, "Single" |
|
30
|
|
|
|