I come from the R language and I gradually switch to Python (Numpy and Pandas). I coded this python code for fun to solve a Sudoku grid. Could you tell me if my code is pythonic enough? For example, did I use the numpy functions correctly. How to make the code more readable?
import numpy as np
from functools import reduce
def solver_python(grid):
numbers=np.arange(1,10)
i,j = np.where(grid==0)
if (i.size==0):
return(True,grid)
else:
i,j=i[0],j[0]
row = grid[i,:]
col = grid[:,j]
sqr = grid[(i//3)*3:(3+(i//3)*3),(j//3)*3:(3+(j//3)*3)].reshape(9)
values = np.setdiff1d(numbers,reduce(np.union1d,(row,col,sqr)))
grid_temp = np.copy(grid)
for value in values:
grid_temp[i,j] = value
test = solver_python(grid_temp)
if (test[0]):
return(test)
return(False,None)
example = np.array([[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]])