-
Notifications
You must be signed in to change notification settings - Fork 2
/
count-neighbours.py
32 lines (28 loc) · 1.2 KB
/
count-neighbours.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def count_neighbours(grid, row, col):
begR = max(row - 1, 0)
begC = max(col - 1, 0)
endR = min(row + 2, len(grid))
endC = min(col + 2, len(grid[0]))
sum = 0
for r in range(begR, endR):
for c in range(begC, endC):
sum += grid[r][c]
return sum - grid[row][col]
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 1, 2) == 3, "1st example"
assert count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 0, 0) == 1, "2nd example"
assert count_neighbours(((1, 1, 1),
(1, 1, 1),
(1, 1, 1),), 0, 2) == 3, "Dense corner"
assert count_neighbours(((0, 0, 0),
(0, 1, 0),
(0, 0, 0),), 1, 1) == 0, "Single"