# 7-11/19 why len(board)-1?

#1

I looked through the forum and figured out the correct code, but I do not understand why using this works:

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

in this case of the 5x5 space for battleship, it means it finds a random integer say, N, between index 0 and 4, not including index 4.

can someone explain why we use:
len(board[0])-1

``````import random

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 random.randint(0, len(board)-1)
def random_col(board):
return random.randint(0, len(board[0])-1)

print random_row(board)
print random_col(board)``````

#2

Somewhere along the line a learner decided that the lesson didn't make human sense since it uses indexes, not counting (natural) numbers for the inputs. He didn't like the way the lesson was instructed so took the attitude, "I'm going to make this better."

It has led to a ream of questions in the forums as learners run into this modified code and get stopped in their tracks, scratching their heads. Whomever opened this can of worms did not do anybody any favors. It is, after all, only us who are running the code, and as the author we are aware of the expected inputs... `0 .. 4`. Insisting we use, `1 .. 5` is a trivial demand and one that I wish had never come up.

For best results, follow the instructions and stick to the lesson plan.

#3

I was only asking why it worked because I am a confused beginner. I was not insisting anything. I was just asking a question. I AM sticking to the lesson plan all I wanted was someone to EXPLAIN it to me. Please do not misunderstand I was only trying to ask for help.

#4

Totally mistook your question. My apologies.

Is it that -1 that you are confused with? That is simply the needed reduction so the random number is in the range. 0 .. 4. The length of an array is always 1 more than the last index.

#5

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