Skip to content
Advertisement

Checking If Position Exists in Nested List

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:

  1. Each 1 must be replaced with a 9
  2. 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:

  counter = 0
  if x+1 < len(board):
    if board[x+1][y] == 9:
      counter += 1
  if y+1 < len(board[i]):
    if board[x][y+1] == 9:
      counter += 1
  if x-1 >= 0:
    if board[x-1][y] == 9:
      counter += 1
  if y-1 >= 0:
    if board[x][y-1] == 9:
      counter += 1
  board[x][y] = counter

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:

...

# suppose the current position is (x,y)
for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
    tx = x + dx # t as in target
    ty = y + dy
    if 0 <= tx < len(board) and 0 <= ty < len(board[tx]):
        # the position (tx, ty) exists, do whatever you want with it
        pass
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement