This forum is now read-only. Please use our new forums! Go to forums

banner
Close banner
0 points
Submitted by Sam Seidenberg
over 11 years

Why len(board[0]) - 1) ?

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

What exactly are len(board) - 1 and len(board[0]) - 1 doing? And what’s the difference between the two? I have a vague idea, just trying to get a clearer picture.


updated by Michael Rochlin for code formatting. (See here for how to do it.)

Answer 50a417447048c82e9c0006d4

19 votes

Permalink

len(board) - 1 is one less than the number of rows in board. len(board[0]) - 1 is one less than the number of columns. (board[0] is the first row in board and all rows are the same length.)

if there are 5 rows, they have indexes 0,1,2,3,4 so the highest random number we want is 4 which is len(board) - 1

Hope that helps.

points
Submitted by Michael Rochlin
over 11 years

7 comments

Sam Seidenberg over 11 years

Very helpful, thanks Michael!

Michael Rochlin over 11 years

no problem. Happy coding!

Setor over 11 years

@Michael: So randint(x,y) actually generates a random number between x and y, inclusive?

Michael Rochlin over 11 years

yes

Alex J over 11 years

yeah, that was ambiguous. I searched the online python documentation to be sure, and it says: “random.randint(a, b) Returns a random integer N such that a <= N <= b.”

carnage1325gmail.com about 11 years

SHould’nt this whole thing be the opossite ? len(board[0]) -1 for row position and len(board) for column position

Deep L Sukhwani about 11 years

by default indexes work primarily for rows and not columns as lists are defined as rows a list looks like a row visually so list[0] gives first element of a row.

Answer 50b13ad7d4e2b6c145000377

4 votes

Permalink

Why cant you use (0, len(board)-1) for both random_row and random_col??? Aren’t they both 4?? Why do you have to use (0,len(board[0]-1) for random_col??

points
Submitted by Sara Marchioni
over 11 years

3 comments

Olav Cleemann over 11 years

I think the idea is, that in this way you can change the size of the board in boths dimensions and not have to change the logic for generating the random posistion. In fact if the size is always given and always quadratic, you could just make one simple function and not even pass the board as parameter.

Peter Shin over 11 years

Makes sense now, thanks for the explanation phluks!

njsleep over 11 years

If the board were always a square (i.e. 5 x 5, 6 x 6, 7 x 7, etc) then it wouldn’t matter at all, you could use the same function to generate both the row and column. Doing it this way allows for non-square rectangular boards.