Search code examples
python-3.xlistrangetic-tac-toe

Determining if all items in a range are equal to a specific value


This question is related to the tic tac toe problem using python: Let's say I have a list - my_list = ['X', 'O', 'X', 'O', 'X', '-', 'O', 'X', 'X']. I want to determine if all the items in range(0, 2) or range(3, 5) or range(6, 8) == X So far I have tried the following, but get a syntax error:

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')

The problem really stems from setting up the range on the second line, but I also feel I am not using the all function correctly. Can you shed light my mistake here? Side note: I also want to check to see if index items[0, 3, 6], [1, 4, 7], and [2, 5, 8]-the "columns" as well as the diagonals index[0, 4, 8] and [6, 4, 2] are all of a specific value.


Solution

  • Listing the winner indices explicitly works:

    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')