Simple sudoku puzzle solver python -
i'm trying write simple sudoku solver in python. basic concept sudoku puzzle partially filled in , unsolved cells indicated zeros. cell denoted 0 can solved @ stage of puzzle. if first cell 0, means values in row, column , 3x3 subgrid ensure there can 1 possible value cell. here code, seem stuck because output displays more 1 possibility. algorithm wrong?
def solveone (array, posr, posc): possible = ['1','2','3','4','5','6','7','8','9'] col in range (9): if array[posr][col] in possible: possible.remove(array[posr][col]) row in range (9): if array[row][posc] in possible: possible.remove(array[row][posc]) row in range(posr, posr+3): col in range (posc, posc+3): if array[row::][col::] in possible: possible.remove(array[row][col]) print (possible) return possible grid = [["" _ in range(9)] _ in range(9)] #define 9x9 2-dimensional list row in range(9): aline = input() #prompt user enter 1 line of characters col in range(9): grid[row][col] = aline[col:col+1] #assign every character in line position in 2-d array row in range(9): col in range (9): if grid[row][col] == '0': r = row c = col newv = solveone (grid,r,c) grid[row][col] = newv print() in range (9): k in range(9): print(grid[i][k], end = "") print()
there several mistakes:
for row in range(posr, posr+3): col in range (posc, posc+3): if array[row::][col::] in possible: possible.remove(array[row][col])
will not want do. better try (for python 2.7 - beware of div operation not doing float divison integer division):
block = ((posr/3)*3,(posc/3)*3) # top left cell of 3x3 block row in range(block[0], block[0]+3): col in range (block[1], block[1]+3): if array[row][col] in possible: possible.remove(array[row][col])
so works better. doing
for row in range(9): col in range (9): if grid[row][col] == '0': r = row c = col newv = solveone (grid,r,c) grid[row][col] = newv
you go through sudoku once. it's neccessary solve sudoku in more 1 step through - think that.
and have aware not every sudoku has unique solution. think solving empty sudoku - can pretty "do want".
Comments
Post a Comment