python - Matrix, index out of range -
i've declared matrix following code:
matrix = [[' ' x in range(x1)] x in range(y1)] but when try find random element , change it's value following code:
randomx = random.randint(0, x) randomy = random.randint(0, y) if matrix[randomx][randomy] == ' ': try: matrix[randomx][randomy] = 'g' scr.addstr(randomx, randomy, matrix[randomx][randomy]) scr.refresh() except indexerror: return i indexerror. tried write garbage code exit function if runs in indexerror. works once, still throws error.
note, x1 same x in function. same goes y1 , y.
any clue i'm doing wrong?
your indices in wrong order. should access them by
matrix[randomy][randomx] or change order in comprehension.
matrix = [[' ' y in range(y1)] x in range(x1)] also, garrett pointed out in comments, randint() inclusive on both ends might want use randint(0,x-1) , randint(0,y-1).
Comments
Post a Comment