from random import randint

board = []

for x in range(0,5):
board.append([“O”] * 5)

def print_board(board):
for row in board:
print " ".join(row)

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

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

ship_row = random_row(board)
ship_col = random_col(board)

I just wonder why it before this section, the code was:

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

and in …Seek section, it changed to

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

Why was that?


because if you have a board which doesn’t have the same number rows as columns, return randint(0, len(board) - 1) might produce a ship column which doesn’t exist


But in this case, the number of row is equal to the number of columns (5x5)…


in this case, yes. But maybe some day you want to change your board dimensions and then you spend 30 minutes debugging why you sometimes get an error, to only figure out random_col function uses the row length

so doing it right now, makes your code less prone to bug when applying changes (better practice)


that’s fair enough. Thanks


Now, i admit in a program this small you will probably find it fairly quickly, but learning good habits (writing maintainable code which is less prone to bugs/changes) now is very valuable

i just spend an hour figuring out that i forgot to change json to html :frowning: Its so easy to change one thing (board) and then forget to update the associated function (random_col, or json to html in my case)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.