干净的方式写这个如果
Clean way to write this if
您好,我正在编写 python 函数,当我尝试使用 pylint 对其进行测试时,它显示:R0912:太多分支 (20/12)(太多分支)。我应该如何在更干净的下面编写这段代码?
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
制作两个列表:
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
那么你可以把if部分写成:
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
您好,我正在编写 python 函数,当我尝试使用 pylint 对其进行测试时,它显示:R0912:太多分支 (20/12)(太多分支)。我应该如何在更干净的下面编写这段代码?
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
制作两个列表:
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
那么你可以把if部分写成:
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