Advertisement
Guest User

sudoku

a guest
Oct 19th, 2019
694
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. def solve_sudoku(file_name):
  2.     ''' Solves sudoku given in a .txt file'''
  3.  
  4.     list_of_empties = None
  5.  
  6.     #TODO: Open up file and get a Python readable grid
  7.     sudoku_grid = get_grid_from_file(file_name)
  8.  
  9.     #TODO: Get length of sudoku
  10.     column_length = len(sudoku_grid)
  11.     row_length = len(sudoku_grid[1])
  12.  
  13.     while len(list_of_empties) > 0 or list_of_empties == None:
  14.     #Returns a list of all the empty blanks and the possible valid entries in each blank
  15.  
  16.  
  17.         #TODO: Check all the blanks for valid entries
  18.         for r in range(row_length):
  19.             for c in range(column_length):
  20.                 #Finds and checks the value in the r-th row and c-th column if it is empty.
  21.                 if subgrid_values(sudoku_grid,r,c) == 'x':
  22.                     list_of_valid_entries = []
  23.                    
  24.                     #Checks all the possible valid entries for that particular blank of the sudoku
  25.                     for i in range (1,10):
  26.                         if valid_entry(sudoku_grid,i,r,c):
  27.                             list_of_valid_entries.append(i)
  28.                            
  29.                     #Stores the infomation (the number of possible valid entries to the blank, the list of valid entries, the row and column of the empty) in a list of all the empty blanks.
  30.                     list_of_empties.append([len(list_of_valid_entries),list_of_valid_entries,r,c])
  31.  
  32.         #TODO: Solve starting with the blanks with the least number of valid entries.
  33.         least_valid_entry = None
  34.    
  35.         for empty in list_of_empties:
  36.             #Finds the empty blanks with the least number of valid entries
  37.             if least_valid_entry == None:
  38.                 least_valid_entry = empty
  39.              elif empty[0] < least_valid_entry[0]:
  40.                 least_valid_entry = empty
  41.            
  42.         #If there is only one valid entry for that empty blank, replace the empty blank with the values
  43.         if least_valid_entry[0] == 1:
  44.             sudoku_grid[least_valid_entry[3]][least_valid_entry[2]] = least_valid_entry[1][0]
  45.  
  46.         #Repeats the process till there is no more empty blanks left
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement