Doubt in random_row and random_col functions


#1

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

I need to understand the working of random_row and random_col functions.


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

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


1. How does the length of Grid calculated? If the Grid is 4*5 (4 rows and 5 columns) then what would be the length?

2. Why are we subtracting the length?

3. In the random_col function why are we including index 0 while subtracting from 1, and doing the same for random_row function?

Thanks in advance for help :slight_smile:


#2

There are actually five rows and five columns in this game, zero-indexed.

print randint(0, 5)

could print, 5, which is of no use if there is no index position, 5 in the row or column. This is why,

return randint(0, len(board) - 1)

To ensure that the second argument is never 5, we subtract 1. Now the random integers will be one of 0, 1, 2, 3, 4 but not 5.


#3

@mtf thanks for clarifying mate.

Could you also explain this

I just tried the random_col function by removing the index 0 in the below statement

and there was no change in the output grid.


#4

We may need to pencil through this.

  0 1 2 3 4
0 0 0 0 0 0
1 0 0 0 0 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0

There are five rows in the list, each with a list of five rows, which translate as columns. The lists in the rows behave the same as the list they are contained in.