grid = [[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]]
# 4 for this grid, otherwise len() works
res = [[0] * 4 for i in range(4)]
# use this function to avoid bounds checking
def is_neighbor(x1, y1, x2, y2):
if (x1 == x2 + 1 and y1 == y2) or (x1 == x2 - 1 and y1 == y2) or (x1 == x2 and y1 == y2 + 1) or (x1 == x2 and y1 == y2 -1):
return True
else:
return False
# add numbers arounds point (x,y), including itself
def add_up(x, y):
tf_map = [[0] * 4 for i in range(4)]
for i in range(4):
for j in range(4):
if is_neighbor(x, y, i, j):
tf_map[i][j] = grid[i][j]
tf_map[x][y] = grid[x][y]
sum = 0
for row in tf_map:
for item in row:
sum += item
res[x][y] = sum
return res
# reconstruct the 2-D list
for i in range(4):
for j in range(4):
add_up(i, j)
print(res)
>>
[[5, 8, 12, 12], [17, 25, 30, 27], [33, 45, 50, 43], [33, 48, 52, 40]]