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