2
\$\begingroup\$

Below a function which answers: is there a winner in tic-tac-toe game?

Also, there is a test suite I wrote for it.

def is_win(field):
    # check horizontal
    N = len(field)
    for i in range(N):
        if field[i][0] != 0 and len(set(field[i])) == 1:
            return True
        vertical = [field[j][i] for j in range(N)]
        if vertical[0] != 0 and len(set(vertical)) == 1:
            return True
    # check diagonal
    diagonal = [field[i][i] for i in range(N)]
    if diagonal[0] != 0 and len(set(diagonal)) == 1:
        return True
    o_diagonal = [field[N-i-1][i] for i in range(N)]
    if o_diagonal[0] != 0 and len(set(o_diagonal)) == 1:
        return True
    return False

assert is_win(
        [
            [0, 0, 0],
            [2, 2, 2],
            [0, 0, 0],
            ]) == True

print(1)
assert is_win(
        [
            [0, 2, 0],
            [0, 2, 0],
            [0, 2, 0],
            ]) == True
print(2)
assert is_win(
        [
            [0, 0, 2],
            [2, 2, 1],
            [0, 0, 1],
            ]) == False
print(3)

assert is_win(
        [
            [2, 0, 0],
            [0, 2, 0],
            [0, 0, 2],
            ]) == True
print(4)
assert is_win(
        [
            [0, 0, 2],
            [0, 2, 0],
            [2, 0, 0],
            ]) == True
print(5)
```
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
  • Your code is WET.

    var[0] != 0 and len(set(var)) == 1
    

    Is repeated four times.

  • field[len(field)-i-1] can be simplified to field[~i].

  • I'd personally just use a couple of any and a couple of ors.
def is_unique_player(values):
    return values[0] != 0 and len(set(values)) == 1


def is_win(field):
    N = len(field)
    return (
        any(is_unique_player(row) for row in field)
        or any(is_unique_player(column) for column in zip(*field))
        or is_unique_player([field[i][i] for i in range(N)])
        or is_unique_player([field[~i][i] for i in range(N)])
    )
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.