Reputation: 1657
I am trying to create a simple tictactoe game and am trying to save the rows to a row[] and columns to a columns[] so that I can access each element in the board by doing board[row][col].
I am getting the rows saved when traversing thru the matrix in the first loop but unable to save the column indices. Any thoughts on what im doing wrong and how to do it correctly?
Heres the code:
board = [
['|', '|', '|' ],
['|', '|', '|'],
['|', '|', '|']
]
row = []
col = []
def tictactoe ():
# print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in board]))
for i in range(0,len(board)):
row.append(board[i])
for j in (0, len(board)):
col.append(board[j])
print(row, '!!!!!')
print(col)
Upvotes: 0
Views: 1492
Reputation: 40516
In addition to Fernando's answer explaining what went wrong in your approach and how to solve it, here's how you can achieve the same thing in a simplified manner:
def tictactoe():
rows = board # board is already an array containing the rows.
cols = zip(*board)
print(rows)
print(cols)
Upvotes: 0
Reputation: 1554
Try
board = [
['|', '|', '|' ],
['|', '|', '|'],
['|', '|', '|']
]
row = []
col = []
def tictactoe ():
# print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in board]))
for i in range(0,len(board)):
row.append(board[i])
for j in range(0, len(board[i])):
col.append(board[i][j])
print(row, '!!!!!')
print(col)
Basically in your example you're always acessing only the items of your board
list (i.e the rows), to access a item of a list inside the board
list (i.e the columns), you need to access first the list inside of the boards
array (using board[i]
, for example), and after this you'll complete with the item you want to access, board[i][j]
, for example.
A suggestion is, instead of using for i in range(0, len(board))
, use directly the list iterator, as this: for i in board
. In this case, i
will not be an integer, but the element of the board
variable that you're accessing. Your code will become something like this:
board = [
['|', '|', '|' ],
['|', '|', '|'],
['|', '|', '|']
]
row = []
col = []
def tictactoe ():
# print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in board]))
for i in board:
row.append(i)
for j in i:
col.append(j)
print(row, '!!!!!')
print(col)
Note that the syntax for accessing columns change too: Instead of using board[i][j]
, we just use for j in i
, and the j
variable will contains the column value itself. (as i
is the row contained in board
variable)
Upvotes: 2
Reputation: 21
You forgot range while iterating columns in the following line:
for j in (0, len(board)):
Upvotes: 0