Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

python - 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.

question from:https://stackoverflow.com/questions/65929069/checking-if-position-exists-in-nested-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...