Len(board) vs len(board[o])-1)


#1

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

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

Here the codeacademy system uses functions like above, How they define the random functions differently?

Plus, I do not fully understand how the length function in the second random definitions works? Anyone explain?


#2

This returns a generated random number in the range of row count.

This returns a generated random number in the range of column count.


#3

mtf, my guess is that we understand the statements in your response by virtue of the lesson and instructions. Can you explain HOW the syntax is achieving what you describe?


#4

From my understanding...
First we need to know what len(board) is equal to.
len(board) is the number of lists contained within the list "board", so that number is five.
So we have: return randint(0, 5 - 1) = return randint(0, 4).
Thus we want the computer to generate a random number from 0 to 4; so there are five possible numbers that the computer could choose.
The main thing to remember is that this program is counting 0 as denoting the first row/column instead of 1.
So my question is:
Why do randint(0, len(board) - 1) when you could do randint (1, len(board))?


#5

Why do randint(0, len(board) - 1) when you could do randint (1, len(board))?

randint(0, len(board) - 1) can return 0, 1, 2, 3, 4
randint(1, len(board)) can return 1, 2, 3, 4, 5

Since our board is 5x5 and indexing starts from 0, the latter one can't return the first index 0 and can return 5, which would be out of index.

On the other hand we could write:
randint(1, len(board)) - 1
which returns 0, 1, 2, 3 or 4.


#6

Ah I see. It's bc indexing has to start at 0 instead of 1