'Clean way to write this if
Hi I'm writing python function and when I try to test it with pylint it shows: R0912: Too many branches (20/12) (too-many-branches). How should I write this code below cleaner?
rows = len(board)
cols = len(board[0])
count = 0
copy_board = deepcopy(board)
for i in range(rows):
for j in range(cols):
if check(i - 1, j - 1, rows, cols):
if copy_board[i - 1][j - 1] == 1:
count += 1
if check(i - 1, j, rows, cols):
if copy_board[i - 1][j] == 1:
count += 1
if check(i - 1, j + 1, rows, cols):
if copy_board[i - 1][j + 1] == 1:
count += 1
if check(i, j - 1, rows, cols):
if copy_board[i][j - 1] == 1:
count += 1
if check(i, j + 1, rows, cols):
if copy_board[i][j + 1] == 1:
count += 1
if check(i + 1, j - 1, rows, cols):
if copy_board[i + 1][j - 1] == 1:
count += 1
if check(i + 1, j, rows, cols):
if copy_board[i + 1][j] == 1:
count += 1
if check(i + 1, j + 1, rows, cols):
if copy_board[i + 1][j + 1] == 1:
count += 1
# Apply the rule to each cell
if count < 2 or count > 3:
board[i][j] = 0
elif count == 3:
board[i][j] = 1
# Reset the count for the next cell
count = 0
Solution 1:[1]
Make two lists:dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
then you can write the if part as:
for k in range(len(dx)):
if check(i+dx[k], j+dy[k], rows, cols) and copy_board[i+dx[k]][j+dy[k]]:
count+=1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | WinterSoldier |