Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import numpy as np
- class Sudoku():
- """Class for handling 9x9 sudokus.
- Args:
- input_grid (str): String with the path to a 9 line text
- file with 9 numbers where gaps are
- represented by '0'
- input grid (nda): 9 by 9 numpy array with gaps set as '0'
- Attributes:
- grid (nda): current state of the sudoku grid
- length (int): length of the grid, for now always 9
- sub_length (int): sqrt of the length
- check_sum (int): sum of a unique row/column
- bu_grid (lst): list of backup grids used for guessing
- guesses (int): number of guesses for the current grid
- max_guesses (int): maximal number of guesses for the current grid
- mask (nda): 9x9x9 numpy array (bit mask).
- Example:
- s = Sudoku(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]]))
- s.solve()
- s.print_grid()
- """
- def __init__(self, input_grid):
- """Initialize an instance of the Sudoku class.
- Set up the initial gird based on text or numpy array.
- Next get the length of one of the axis as well as the
- sub length. The check sum is used to validate the grid
- based on unique sum of all digits. The list of back up
- grids is initialized as an empty list together with
- the current guess and the current number of maximal
- guesses. Last the 'bit' mask is set to all zeros.
- """
- self.grid = self.read_grid(input_grid)
- self.length = int(np.sqrt(np.size(self.grid)))
- self.sub_length = int(np.sqrt(self.length))
- self.check_sum = int(np.sum(range(self.length + 1)))
- self.bu_grid = []
- self.guesses = 0
- self.max_guesses = 2
- self.mask = np.zeros([self.length, self.length, self.length])
- def __repr__(self):
- self.print_grid()
- def read_grid(self, input_grid):
- """Parse the sudoku grid.
- Read a text file containing 9 lines with 9 non-spaced digits
- and converts it to numpy array. Blank spaces are represented
- by 0. Alternatively takes a already formatted numpy array as
- input and returns the input as a 9x9 array.
- """
- if isinstance(input_grid, str):
- grid = []
- with open(input_grid) as f:
- text = f.read()
- for line in text.split():
- grid.append([int(element) for element in line])
- return np.array(grid)
- elif isinstance(input_grid, np.ndarray):
- return input_grid
- else:
- raise ValueError('Not a valid input grid')
- def backup_grid(self):
- """Create a list of back up grids.
- Create a back up of of the current grid and guess number to
- have a restore point in case a guess turns out wrong.
- """
- bckup = BackUpGrid(self.grid, self.guesses)
- self.bu_grid.append(bckup)
- def restore_grid(self):
- """Restore the last backup grid.
- If a back up grid is present overwrite the current grid,
- and increase the guess count by one.
- """
- if not self.bu_grid:
- raise ValueError('No backup grid')
- else:
- self.bu_grid[-1].guesses += 1
- bckup = self.bu_grid[-1]
- self.grid = bckup.grid
- self.guesses = bckup.guesses
- def print_grid(self):
- """Print formatted grid."""
- BOLD = '