7/19 curious about alternate code


#1

Hello, for the random integer creation in part 7 I used the following code


from random import randint
def random_row(board_in):
  for row in board_in:
    return randint(0,len(board_in)-1)
  
def random_col(board_in):
  for row in board_in:
    for item in row:
      return randint(0,len(row)-1)
random_row(board)
random_col(board)

The standard code was this:

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

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

Part 7 passed my code, but I would be grateful if the difference between the two codes were explained.


#2

I would pick the exercise code over your code

i just a single value, why would i then want to implement a loop? return will end the function, so then the loop doesn’t add any value

as for return randint(0,len(row)-1) for random_col, i would again pick the exercise solution. What if later you decide you want to change the board and make it 6 by 8. Then your code could cause a bug, where the exercise code doesn’t

always code defensively


#3

Thank you very much for your response.


#4

Does that answer all your questions?


#5

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