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:

JavaScript

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
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement