gpt4 book ai didi

python - 我怎样才能将我的两个 for 循环重新组合成一个,两者之间只有微小的差异?

转载 作者:行者123 更新时间:2023-12-04 17:12:52 25 4
gpt4 key购买 nike

我有以下代码,唯一的区别是列表中的 j 和 I 位置。有什么方法可以通过编写一个函数或类似的东西来让它变得更好,因为我不太明白吗?

for i in range(dimension):
for j in range(dimension - 4):
k = 1
while k < 5 and gameboard[i][j+k] == gameboard[i][j]:
k += 1
if k == 5:
winner = gameboard[i][j]

for i in range(dimension):
for j in range(dimension - 4):
k = 1
while k < 5 and gameboard[j+k][i] == gameboard[j][i]:
k += 1
if k == 5:
winner = gameboard[j][i]

最佳答案

您可以通过插入一个额外的嵌套循环来合并这两个循环,该循环处理 i 和 j 的排列以及相应的维度增量:

for i in range(dimension):
for j in range(dimension - 4):
for i,j,di,dj in [ (i,j,0,1), (j,i,1,0) ]:
k = 1
while k < 5 and gameboard[i+k*di][j+k*dj] == gameboard[i][j]:
k += 1
if k == 5:
winner = gameboard[i][j]

所有方向的通用化

或者,您可以创建一个函数,告诉您在给定方向上是否有胜利,并在循环中使用它。

def directionWinner(board,i,j,di,dj):
player,pi,pj = board[i][j],i,j
# if player == empty: return
for _ in range(4):
pi,pj = pi+di, pj+dj
if pi not in range(len(board)): return
if pj not in range(len(board)): return
if board[pi][pj] != player: return
return player

然后用它来检查所有方向:

for pos in range(dimensions*dimensions):
i,j = divmod(pos,dimensions)
for direction in [ (0,1),(1,0),(1,1),(1,-1) ]:
winner = directionWinner(gameboard,i,j,*direction)
if winner is not None: break
else: continue; break

方向由每一步的垂直和水平坐标 (delta) 的增加/减少表示。所以 [ (0,1),(1,0),(1,1),(1,-1) ] 给你 "down", "across", "diagonal 1", diagonal分别为 2"。

只检查最后一步

同样的想法可以用来检查特定位置的获胜者(例如检查最后一步是否获胜):

# count how may consecutive in a given direction (and its inverse)
def countDir(board,i,j,di,dj,inverted=False):
player,pi,pj = board[i][j],i,j
count = 0
while pi in range(len(board) and pj in range(len(board)):
if board[pi][pj] == player: count += 1
else: break
pi, pj = pi+di, pj+dj
if not inverted:
count += countDir(board,i,j,-di,-dj,True)-1
return count

def winnerAt(board,i,j):
for direction in [ (0,1),(1,0),(1,1),(1,-1) ]:
if countDir(board,i,j,*direction)>=5:
return board[i,j]

然后,在i,j位置下棋后,可以立即知道这步棋是否获胜:

if winnerAt(gameboard,i,j) is not None:
print(gameboard[i][j],"wins !!!")

关于python - 我怎样才能将我的两个 for 循环重新组合成一个,两者之间只有微小的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69143825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com