I am try to practice the leetcode and hit the following question 'image smooth'. Basically the question is to calculate average the around cell value from a 2D array. I have following code. But if there is better way to do it at least better performance?
def imageSmoother(M): """ :type M: List[List[int]] :rtype: List[List[int]] """ import numpy as np from math import floor m_np = np.array(M) tol_r, tol_c = m_np.shape mx = np.zeros(shape=(tol_r, tol_c), dtype=int) for r in range(0, tol_r): for c in range(0, tol_c): row = slice(max(0, r-1), min(tol_r, r + 2)) col = slice(max(0, c-1), min(tol_c, c + 2)) total = m_np[row, col].sum() x, y = m_np[row, col].shape mx[r, c] = floor(total/(x * y)) return mx.tolist()