#!/usr/bin/env python3 from sudoku import Game from copy import deepcopy MAX_V = 9 class State: def __init__(self): resultboard = [] for x in range(MAX_V): temprow = [] for y in range(MAX_V): temprow.append(0) resultboard.append(temprow) self.resultboard = resultboard choicesboard = [] numbers = [] for value in range(1,10): numbers.append(value) for x in range(MAX_V): row = [] for y in range(MAX_V): choices = deepcopy(numbers) row.append(choices) newrow=deepcopy(row) choicesboard.append(newrow) self.choicesboard = choicesboard def printBoard(self): for x in range(MAX_V): if x%3==0: print() for y in range(MAX_V): if y%3==0: print(" ", end="") print(self.resultboard[x][y], end="") print() print() def actions(state): actions = [] for row in range(MAX_V): for col in range(MAX_V): #Value not yet assigned if state.resultboard[col][row] == 0: #Add possible move for num in state.choicesboard[col][row]: move = {'col': col, 'row': row, 'num': num} actions.append(move) return actions def result(state,move): newState = deepcopy(state) newState.resultboard[move['col']][move['row']] = move['num'] return newState def goalTest(state): incomplete = False for row in range(MAX_V): for col in range(MAX_V): if state.resultboard[col][row] == 0: imcomplete = True return incomplete def eliminateIllValues(state): newState = deepcopy(state) for row in range(MAX_V): for col in range(MAX_V): if newState.resultboard[col][row] != 0: num = newState.resultboard[col][row] # Eliminate duplicates numbers in a row for x in range(MAX_V): softRemove(newState.choicesboard[x][row], num) # Eliminate duplicates numbers in a column for y in range(MAX_V): softRemove(newState.choicesboard[col][y], num) # Eliminate duplicates in block (working only for 9x9 cells) #for y in range(MAX_V) # choicesboard[col][y].del(state.resultboard[col][row]) return newState def softRemove(list, target): for item in list: if item == target: list.remove(item) if __name__ == "__main__": node = State() while not goalTest(node) and len(actions(node)) is not 0: move = actions(node).pop() node = result(node,move) node = eliminateIllValues(node) print('Result found!') node.printBoard()