代码之家  ›  专栏  ›  技术社区  ›  gwydion93

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

  •  -1
  • gwydion93  · 技术社区  · 7 年前

    这个问题与使用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] 都是特定值。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Mike Müller    7 年前

    明确列出获奖者指数:

    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')
    
        2
  •  -1
  •   Sohaib Farooqi    7 年前

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

    我的解决方案使用 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]]