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:
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.
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
One way is to use logical short-circuiting:
if x+1 < len(board) and board[x+1][y] == 9:
counter += 1
If the first clause is False
, the second won't be evaluated at all. You're safe from that exception.
Next you can simplify the math: harness the fact that class bool
is a derived from int
: False
is 0; True
is 1.
counter += x+1 < len(board) and board[x+1][y] == 9
Now, you can just put all four liens in a row, or even combine all four Boolean expressions into a single +=
statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.