This forum is now read-only. Please use our new forums! Go to forums
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
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.
Answer 50b13ad7d4e2b6c145000377
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??
3 comments
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.
Makes sense now, thanks for the explanation phluks!
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.
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
7 comments
Very helpful, thanks Michael!
no problem. Happy coding!
@Michael: So randint(x,y) actually generates a random number between x and y, inclusive?
yes
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.”
SHould’nt this whole thing be the opossite ? len(board[0]) -1 for row position and len(board) for column position
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.