I have a function within a Python (2.7) class that should retrieve the values of the ‘cells’ around it in a 2 dimensional numpy array. If the index is out of range, I would the value should be set as None.
I’m struggling to find a way to do this without writing 8 try/catch statements, or without using multiple if x else None statements as is in my code below. While they would both work, they don’t seem very well structured, and I’m thinking there must be a simpler way to do this – I’m probably caught thinking about this in entirely the wrong way. Any help would be much appreciated.
# This will return a dictionary with the values of the surrounding points
def get_next_values(self, column, row):
if not (column < self.COLUMNS and row < self.ROWS):
print "Invalid row/column."
return False
nextHorizIsIndex = True if column < self.COLUMNS - 2 else False
nextVertIsIndex = True if row < self.ROWS - 2 else False
n = self.board[column, row-1] if column > 0 else None
ne = self.board[column+1, row-1] if nextHorizIsIndex else None
e = self.board[column+1, row] if nextHorizIsIndex else None
se = self.board[column+1, row+1] if nextHorizIsIndex and nextVertIsIndex else None
s = self.board[column, row+1] if nextVertIsIndex else None
sw = self.board[column-1, row+1] if nextVertIsIndex else None
w = self.board[column-1, row] if row > 0 else None
nw = self.board[column-1, row-1] if 0 not in [row, column] else None
# debug
print n, ne, e, se, s, sw, w, nw
Here is a standard trick: Create your board with an edge padded with the value None. Then you can access any inner 3×3 square and fill in the appropriate values with
For example,
Note that
and the second index as the column, because when you
print(board)that is the way the values are formatted. So perhaps you want
board[row-1:row+2, column-1:column+2]instead. Of course, you could define your ownprint_boardfunction, and then be free to use whatever convention you like.