Skip to content
Advertisement

Numpy 2D-array sets the value of a cell when it is not needed

I’m trying to write minesweeper in python. A bomb is a cell with a value less than 0. The values of cells that differ from the position of the bomb cell by one column and one row in all directions should increase by 1. But the values of cells that are far from the bomb often increase. Please help me

JavaScript

enter image description here

Replacing np.full with np.zeros, changes in the replacement algorithm do not help

New setnumbers function:

JavaScript

13

Advertisement

Answer

The problem is: since indexing negative positions in numpy arrays returns actual elements of the structure (e.g. a[-1] returns the last element), you are adding more than what is necessary because the except IndexError: doesn’t catch any error (-1 is a valid index).

JavaScript

I removed the unnecessary except. There are much more pythonic and efficent ways of checking index overflow (e.g. compare it with array.shape).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement