确定范围中的所有项目是否等于特定值

问题描述 投票:-1回答:2

这个问题与使用python的tic tac toe问题有关:假设我有一个列表 - my_list = ['X', 'O', 'X', 'O', 'X', '-', 'O', 'X', 'X']。我想确定range(0, 2) or range(3, 5) or range(6, 8) == X中的所有项目到目前为止我已尝试过以下内容,但是出现语法错误:

my_list = ['X', 'O', 'X', 'O', 'X', '-', 'O', 'X', 'X']

for i in range(0, 3):
    if all(board[i]) == 'X':
        print('X is the winner')
    elif all(board[i]) == 'Y':
        print('Y is the winner')

问题实际上源于在第二行设置范围,但我也觉得我没有正确使用all函数。你能在这里揭露我的错误吗?旁注:我还想检查索引items[0, 3, 6][1, 4, 7][2, 5, 8]-“列”以及对角线index[0, 4, 8][6, 4, 2]是否都是特定值。

python-3.x list range tic-tac-toe
2个回答
2
投票

明确地列出获胜者指数:

my_list = ['X', 'O', 'X', 'O', 'X', '-', 'O', 'X', 'X']

winner_indices = [[0, 1, 2], [3, 4, 5], [6, 7, 8],
                  [0, 3, 6], [1, 4, 7], [2, 5, 8],
                  [0, 4, 8], [6, 4, 2]]

no_winner = True
for indices in winner_indices:
    selected = [my_list[index] for index in indices]
    for party in ['X', 'O']:
        if all(item == party for item in selected):
            print('{} is the winner'.format(party))
            no_winner = False
if no_winner:
    print('nobody wins')

-1
投票

在决定获胜者时,您没有考虑所有获胜组合。我将使用的方法可用于以通用方式生成获胜组合网格。即使你想扩展,这也会有所帮助。

我的解决方案使用numpy包。如果您还没有安装它。

import numpy as np
from itertools import chain

#Define size of your grid
n_dim = 3

#Input list from players
my_list = ['X', 'O', 'X', 'O', 'X', '-', 'O', 'X', 'X']

#Generate a n_dim*n_dim grid and reshape it in rows and columns
grid = np.arange(n_dim*n_dim).reshape(n_dim, n_dim)

#Get all rows and columns out from the grid as they all are winning combinations
grid_l = list(chain.from_iterable((grid[i].tolist(), grid[:,i].tolist()) for i in range(n_dim)))

#Get the forward diagonal
grid_l.append(grid.diagonal().tolist())

#Get reverse diagonal
grid_l.append(np.diag(np.fliplr(grid)).tolist())

#Check if any player's combination matches with any winning combination
result = [i for i in grid_l if all(my_list[k] == 'X'  for k in i) or all(my_list[k] == 'O' for k in i)]
#result [[0,4,8]]
© www.soinside.com 2019 - 2024. All rights reserved.