Battleship - Columns


#1



https://www.codecademy.com/en/courses/python-beginner-en-4XuFm/2/1?curriculum_id=4f89dab3d788890003000096


This code is the correct code for the Battleship exercise. I was just wondering if anyone can explain how columns work in this exercise. The entire time while I was working through the exercises my "X" s would take up the entire row until this last exercise where I find this code defining columns, which fixed the problem. Why does this work as a column selection for the board?


def random_col(board):
    return randint(0, len(board[0]) - 1)


#2

Reference objects cannot be copied, only referenced. If you start off with a row, and then append a copy to the list, you will end up with two rows, but only one reference since both rows are the one object. A change to one row will reflect in the other.

We need to develop our board to have independent cells and rows.

for row in range(len(board)):
    board.append(['O'] * 5)

This will give us the five independent rows, each with five independent cells (the columns).


#3

Would you explain how it creates columns a little more?
I don't fully understand it and I tried just copy/pasting but got an error.

Thanks


#4

>>> ['O'] * 5
['O', 'O', 'O', 'O', 'O']
>>>

To demonstrate independence...

>>> row = ['O'] * 5
>>> row[0] = 'X'
>>> row
['X', 'O', 'O', 'O', 'O']
>>>

Let's start with a list that has 5 rows and one column:

>>> board = []
>>> for row in range(5):
	board.append(['O'])

	
>>> board
[['O'], ['O'], ['O'], ['O'], ['O']]
>>>

Note that we have created a list in each row (pretend this is standing on end).

Now let's extend each row so there are five columns in each one.

>>> for row in range(len(board)):
	board[row] *= 5

	
>>> board
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
>>>

Now when we pretty print,

>>> for row in board:
    print (' '.join(row))

    
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
>>>

To access a cell in the board, we need a row index and an element index within that row: board[row][col]

>>> board[2][2] = 'X'
>>> for row in board:
    print (' '.join(row))

    
O O O O O
O O O O O
O O X O O
O O O O O
O O O O O
>>>

Starting to make sense? Let us know if this needs further explanation.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.