这个问题与使用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]
- "列"以及对角线索引[0, 4, 8]
和[6, 4, 2]
都是特定值。
答案 0 :(得分: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 :(得分:-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]]