这个函数需要一些tictactoe板并返回合法尝试的动作(-1代表“O”,1代表“X”,0是空格)
def legal_locations(boards, moves):
legal_idxs, legal_locs = [], []
illegal_idxs, illegal_locs = [], []
for i, j in enumerate(moves):
# The middle index here is 0 because the locations > 0 are reserved for historical states.
# We only want to examine the current board state.
if boards[i][0][j]: # This location is occupied
illegal_idxs.append(i)
illegal_locs.append(j)
else: # unoccupied
legal_idxs.append(i)
legal_locs.append(j)
return (legal_idxs, legal_locs), (illegal_idxs, illegal_locs)
它工作正常,但“boards”只是一个矩形 numpy 数组,“moves”是一个列表。我认为必须有一种更快的方法来使用 numpy 完成此任务。有任何想法吗?
如果它不能提高效率 - 很高兴知道这个问题是什么使它难以优化。
编辑:
boards =
array([[[ 0, 1, 0, -1, 0, 0, 0, -1, 0],
[ 0, 1, 0, 0, 0, 0, 0, -1, 0],
[ 0, 0, 0, 0, 0, 0, 0, -1, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 1, -1, 0, 0, 0, -1],
[ 0, 0, 0, 1, -1, 0, 0, 0, 0],
[ 0, 0, 0, 0, -1, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0]]])
这个棋盘数组显示了两个游戏,每个游戏都有 4 个历史状态。
moves =
[2, 8]
此移动数组显示两个索引。因此,感兴趣的位置是:
boards[0][0][2]
boards[1][0][8]
所以在这个例子中,我们会从我们的 fxn 中得到以下回报:
([0], [2]), ([1], [8])
EDIT2:一个更核心的例子:
@AlexanderCécile 我想问题的一部分是我不知道如何使用列表作为索引。例如,我不知道如何减少这个循环......
for i in range(legal.shape[0]):
legal[i, 0, index_list[i]] = -1
其中 len(index_list) == len(legal)
如果我能做到这一点,那么其他一切都应该使用 np.nonzero