I have an assignment for writing a Sudoku solver and have achieved the functionality required but a lot of the code is "ugly" and I'm wanting to simplify it but unsure how to.
def hiddenSingleCol(snapshot, cell): j = cell.getCol() # Get column number for cell colCells = snapshot.cellsByCol(j) # Get all cells in that column for num in cell.getAvailNum(): # For each available number for the cell we are looking at hidden = True # Is it a hidden single? (set hidden as True to start) for tempCell in colCells: # For each cell in the list of cells if tempCell == cell: # If it is our cell, ignore pass elif num in tempCell.getAvailNum(): # If one of the available num is the same hidden = False # Set hidden to false break if hidden: cell.setAvailNum(num) # If hidden is still true, set available num to num break
More code snippets:
for cell in cUnsolved: # we're only interested in cells without assigned values updateAvailNums(snapshot, cell) # update the list of potential answers for each cell for cell in cUnsolved: hiddenSingleCol(snapshot, cell) hiddenSingleRow(snapshot, cell) hiddenSingleBlock(snapshot, cell) for cell in cUnsolved: if (len(cell.getAvailNum()) == 0): # and if any have no possible numbers, this is a failed solution return None if (len(cell.getAvailNum()) == 1): # and if there are any with only one possibility, we do this first x = cell.getRow() y = cell.getCol() break elif (len(cell.getAvailNum()) < minNum): # otherwise we are interested in the cell with the least possible numbers so far x = cell.getRow() y = cell.getCol() minNum = len(cell.getAvailNum())
Not only are the multiple
for-loops in here ugly, but I have 2 other versions, slightly altered, for the row and 3x3 blocks. I've tried looking at other code snippets on this but I seem incapable of applying it to my own work.