0

As part of a Python MOOC I am taking, I want to better understand the use of generator.

There's an exercise of tic-tac-toe, I want to implement the check for a winning board using generator.

For detecting a winning column I create 3 different generators, Is there an option to create a generator to create all 3 generator objects?

board = [['x', '.', '.'], ['.', 'o', '.'], ['x', '.', '.']]

player_mark = 'x'
col1_winner = all(mark== player_mark for (mark, _, _) in board)
col2_winner = all(mark== player_mark for (_, mark, _) in board)
col3_winner = all(mark== player_mark for (_, _, mark) in board)

For detection of a win in a row I wrote this:

any(mark1 == mark2 == mark3 == player_mark for (mark1, mark2 , mark3) in board)

how-to-check-if-all-elements-of-a-list-matches-a-condition was helpful but not enough for the general case of creating generators.

joepol
  • 744
  • 6
  • 22

2 Answers2

1

You can use zip(*board) to get an iterator of columns. For example:

board = [['x', '.', 'x'], ['x', 'o', '.'], ['x', '.', '.']]

player_mark = 'x'
col_win = any(all(mark == player_mark for mark in col) for col in zip(*board) )
col_win 
#True

This could then have a nice symmetry with the rows:

row_win = any(all(mark == player_mark for mark in row) for row in board )
Mark
  • 90,562
  • 7
  • 108
  • 148
0

If you use a numpy array you can find the row,col sums with np.sum and the diagonals pretty easily as well with np.trace -

import numpy as np
x=np.array([[1,0,-1],[0,1,-1],[-1,0,1]])
-->array([[ 1,  0, -1],
          [ 0,  1, -1],
          [-1,  0,  1]])

np.sum(x,axis=1)
-->array([0, 0, 0])

np.sum(x,axis=0)
-->array([ 0,  1, -1])

np.trace(x)
-->3

np.trace(np.fliplr(x))
-->-1
jeremy_rutman
  • 3,552
  • 4
  • 28
  • 47