-1

Hi I am pretty new at coding and I was looking for some tips to make my code look more clean (improve my style)

Is there a better way to loop twice rather than using 2 for loops?

The code is supposed to do this.

obnoxious screen shot of text

def solution(matrix):
    new_matrix=[]
    
    for i in range(len(matrix)):
        new_matrix.append([])
        for j in range(len(matrix[0])):
            new_matrix[i].append(0)
            
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            for k in [-1,0,1]:
                for l in [-1,0,1]:
                    if 0<=i+k<=len(matrix)-1 and 0<=j+l<=len(matrix[0])-1:
                        if (matrix[i+k][j+l]==True) and ((i,j)!=(i+k,j+l)):
                            new_matrix[i][j]+=1
    return new_matrix
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    Please [don’t post images of code, error messages, or other textual data.](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors) – tripleee Oct 05 '22 at 09:07
  • 1
    This sort of question should be posted on code-review, not SO. – Julien Oct 05 '22 at 09:07

1 Answers1

1

Consider using Numpy. It's a widely used package that allows high performance computing on n-dimensional arrays. Example solution (using 2d convolution):

import numpy as np

def conv2d(a, f):
    s = f.shape + tuple(np.subtract(a.shape, f.shape) + 1)
    strd = np.lib.stride_tricks.as_strided
    subM = strd(a, shape = s, strides = a.strides * 2)
    return np.einsum('ij,ijkl->kl', f, subM)
    

mines = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]) # 1 for bomb, 0 for empty tile
mines_padded = np.pad(mines, ((1, 1), (1, 1)), mode="constant", constant_values=0)
kernel = np.pad([[0]], ((1, 1), (1, 1)), mode="constant", constant_values=1)
solution = conv2d(mines_padded, kernel)
print(solution)
pcj3
  • 11
  • 2