I’m trying to solve a Python coding problem. Given a certain array containing only 1’s and 0’s I must write a program that returns an array following a few rules:
- Each 1 must be replaced with a 9
- Each 0 must be replaced with the amount of 1’s in its immediate surroundings (above, below, left, right)
I’m having trouble with the edges and corners, since I must first check if a certain position exists to then check if it is a 1. The solution I have right now is to make use of 8 ‘if’ statements, but it looks quite ugly and seems inefficient:
JavaScript
x
15
15
1
counter = 0
2
if x+1 < len(board):
3
if board[x+1][y] == 9:
4
counter += 1
5
if y+1 < len(board[i]):
6
if board[x][y+1] == 9:
7
counter += 1
8
if x-1 >= 0:
9
if board[x-1][y] == 9:
10
counter += 1
11
if y-1 >= 0:
12
if board[x][y-1] == 9:
13
counter += 1
14
board[x][y] = counter
15
While it does work, I was wondering if there was an easier/cleaner solution I could implement.
Advertisement
Answer
It’s not clear to me how that code snippet fits in your solution, but if your problem is the neighborhood iteration, a common trick is to pre-define the offsets:
JavaScript
1
10
10
1
2
3
# suppose the current position is (x,y)
4
for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
5
tx = x + dx # t as in target
6
ty = y + dy
7
if 0 <= tx < len(board) and 0 <= ty < len(board[tx]):
8
# the position (tx, ty) exists, do whatever you want with it
9
pass
10