Codeacademy Battleships 7/19 Python Course
def random_row(board): return randint(0 , len(board) - 1) def random_col(board): return randint(0, len(board)-1) My question is why is (len(board) - 1) instead of len(bo
Solution 1:
The random module has two functions that generate a random integer given a range.
- randint(A, B), returns an integer X such as A <= X <= B
- randrange(A, B), returns an integer X such as A <= X < B. This is very similar to how the range function works
The main difference is that the first range is closed while the second one is open from the right.
In your example, randint(0, len(board))
would possibly return len(board) which would in turn raise an IndexError
as the index of elements in the array are in 0 <= i < len(board)
You could use randrange(len(board))
which is more concise.
Solution 2:
In Python, Arrays start at index 0. So the last item in the array will have an index one less than the length of the array.
For example if the array has three items you have item[0], item[1]. and item[2]. If you tried item[3] than you'd get an exception as there is no such object.
Post a Comment for "Codeacademy Battleships 7/19 Python Course"