Hide... and seek!


#1

This is the code:

from random import randint

board = []

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

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

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

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

So what I want to understand is why when we define the random_row function we type this

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

with len(board) - 1 without the square brackets and this


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

with len(board[0]) - 1 with square brackets?

Because when we type list[index] is beacause we’re trying to have access to the element of that index, right?

So why do I want to access the element [0] of the board[] list?


#2

Hi @paulo191,

board represents a rectangle consisting of rows and columns.

len(board) is the number of rows.

len(board[0]) is the number of elements within row 0, which is the number of columns. In actuality, all the rows actually have the same number of elements.

Since the Battleship! board is a special case of a rectangle, namely a square, the number of rows and columns turns out to be the same, and we could have used len(board) for both the number of rows and columns. However, if we modified the game to use a rectangular board that is not a square, we would need to use len(board[0]) to ensure that the number of columns was specified correctly, so we chose to do it that way here. The code is more robust this way, since such a modification of the dimensions of the board would be less likely to introduce a bug.

EDITED January 29, 2018 to add details to the explanation.


#3

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