# Hide... and Seek

#1

def random_row(board):
return randint(0, len(board) - 1)

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

I don't understand that in the "hide" exercise I typed
def random_col(board):
return randint(0, len(board) - 1)
But it changed once I came to the ... and seek exercise(to the code given at top)

What is the exact difference it creates in the code?

``````from random import randint

board = []

for x in range(0,5):
board.append(["O"] * 5)

def print_board(board):
for row in board:
print " ".join(row)

def random_row(board):
return randint(0, len(board) - 1)

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

ship_row = random_row(board)
ship_col = random_col(board)
print ship_col
print ship_row

guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))``````

#2

this code:

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

is slightly better, if you ever where to create an board which doesn't have the same number of row and columns, this ensures your get the length of column.

#3

How is "len(board)-1" telling us the lenght of the rows and "len(board[0])-1" the length of the columns

#4

`len()` will give use the length of the list/number of items in the list. given this is our 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']]``

there are 5 lists inside the list, so `len(board)` is 5, we subtract one for the fact that list are zero index based

`board[0]` will give us access to the first row:

``['O', 'O', 'O', 'O', 'O']``

and len will count the number of items, which again is 5. again we subtract one to compensate for the fact that lists are zero index based

#5

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