The sudokutools library

Yet another python sudoku library.

sudokutools is a collection of functions and classes, which enable you to read, create, analyze, solve and print sudokus.

Package modules:
  • sudokutools.generate: Create new sudokus.
  • sudokutools.solve: Low-level solving and checking of sudokus.
  • sudokutools.sudoku: Parse, print and compare sudokus.

sudokutools.sudoku - Parsing, printing and comparing

Parse, print and compare sudokus.

Classes defined here:
  • Sudoku: Represents a sudoku.
Functions defined here:
  • column_of(): Returns all coordinates in the column of a given field.
  • row_of(): Returns all coordinates in the row of a given field.
  • square_of(): Returns all coordinates in the square of a given field.
  • surrounding_of(): Returns all surrounding coordinates of a given field.
class sudokutools.sudoku.Sudoku[source]

Bases: object

Represents a sudoku.

This class provides methods to read, write, copy and display data to and from a sudoku as well as compare one sudoku with another. It stores 9x9 fields and the numbers and candidates within these fields.

Coordinates for row and column access are values from 0 to 8 (including). Using other values will most likely raise an IndexError (even though negative numbers are supported, they should not be used).

Overview:

Data access (read, write):
  • __getitem__()
  • __setitem__()
  • get_candidates()
  • set_candidates()
  • remove_candidates()
Copying:
  • copy()
Comparing:
  • empty()
  • __len__()
  • __eq__()
  • diff()
Printing:
  • __str__()
  • encode()
Parsing:
  • decode()
__eq__(other)[source]

Return if other is equal in all fields.

Parameters:other (Sudoku) – Most likely another Sudoku instance, but any object, which can be accessed by other[row, col] is valid.
Returns:
True, if all fields are equal and false if not or other
is an incompatible type.
Return type:bool
__getitem__(key)[source]

Return the number in the field referenced by key.

Parameters:key (int, int) – row and column of the requested field. Must be in range(0, 9).
Returns:The number in the given field, 0 representing an empty field.
Return type:int
Raises:IndexError – if the given coordinates are not valid.
__len__()[source]

Return the number of non-empty fields in this sudoku.

Returns:The number of non-empty fields within this sudoku.
Return type:int
__setitem__(key, value)[source]

Set the number in the field referenced by key to value.

Parameters:
  • key (int, int) – row and column of the requested field. Must be in range(0, 9).
  • value (int) – The number to set the field to, 0 representing an empty field.
Raises:

IndexError – if the given coordinates are not valid.

__str__()[source]

Return sudoku as a human-readable string.

Returns:String representing the sudoku.
Return type:str
copy(include_candidates=False)[source]

Returns a copy of this sudoku.

Parameters:include_candidates (bool) – Whether to copy candidates as well.
Returns:The new sudoku instance.
Return type:Sudoku
classmethod decode(s)[source]

Create a new sudoku from the string s.

Parameters:s (str) – A string representing the sudoku (see below).
Returns:The newly created Sudoku instance.
Return type:Sudoku
Examples for s:
000030000005009602008004013020060000703040106000080090210300800306800700000020000 000030000005009602008004013020060000703040106000080090210300800306800700000020000|124,235

Whitespace is ignored while parsing the string, so you can place newlines for better readability.

Each number represents the value of a column. If a row is full, we continue in the next one. So the sudoku above looks like this:

      |   3   |
    5 |     9 | 6   2
    8 |     4 |   1 3
------+-------+------
  2   |   6   |
7   3 |   4   | 1   6
      |   8   |   9
------+-------+------
2 1   | 3     | 8
3   6 | 8     | 7
      |   2   |

The second string additionally defines candidates. Each set of candidates is separated by ‘,’ so the string above defines the candidates for (0, 0) to be 1, 2 and 4 and for (0, 1) to be 2, 3 and 5

This is the default format, which encode() uses and no other format is supported right now.

diff(other)[source]

Iterate through coordinates with different values in other.

Compares each field in other to the corresponding field in self and yields the coordinates, if the number within is different.

Parameters:other (Sudoku) – Most likely another Sudoku instance, but any object, which can be accessed by other[row, col] is valid.
Yields:(int, int) – row and column of the next different field.
empty()[source]

Iterate through the coordinates of all empty fields.

Yields:(int, int) – row and column of the next empty field.
encode(row_sep='', col_sep='', include_candidates=False)[source]

Return sudoku as a (machine-readable) string.

This method is mainly provided to output sudokus in a machine-readable format, but can be used for creating nicely looking representations as well.

Parameters:
  • row_sep (str) – Separator between rows.
  • col_sep (str) – Separator between columns.
  • include_candidates
Returns:

String representing this sudoku.

Return type:

(str)

For examples of default output string see decode().

get_candidates(row, col)[source]

Return the candidates of the field at (row, col).

Parameters:
  • row (int) – The row of the field.
  • col (int) – The column of the field.
Returns:

The candidates at (row, col).

Return type:

frozenset

get_number(row, col)[source]

Same as sudoku[row, col].

remove_candidates(row, col, value)[source]

Remove the given candidates in the field at (row, col).

Ignores candidates, which are not present in the field.

Parameters:
  • row (int) – The row of the field.
  • col (int) – The column of the field.
  • value (iterable) – The candidates to remove.
set_candidates(row, col, value)[source]

Set the candidates of the field at (row, col) to value.

Parameters:
  • row (int) – The row of the field.
  • col (int) – The column of the field.
  • value (iterable) – The candidates to set the field to.
set_number(row, col, value)[source]

Same as sudoku[row, col] = value.

sudokutools.sudoku._quad_without_row_and_column_of(row, col)[source]

Return some coordinates in the square of (col, row) as a list.

The coordinates in the same row and column are removed.

This is an internal function and should not be used outside of the sudoku module.

sudokutools.sudoku.column_of(row, col, include=True)[source]

Return all coordinates in the column of (col, row) as a list.

Parameters:
  • row (int) – The row of the field.
  • col (int) – The column of the field.
  • include (bool) – Whether or not to include (row, col).
Returns:

list of pairs (row, column) of all fields in

the same column.

Return type:

list of (int, int)

sudokutools.sudoku.row_of(row, col, include=True)[source]

Return all coordinates in the row of (col, row) as a list.

Parameters:
  • row (int) – The row of the field.
  • col (int) – The column of the field.
  • include (bool) – Whether or not to include (row, col).
Returns:

list of pairs (row, column) of all fields in

the same row.

Return type:

list of (int, int)

sudokutools.sudoku.square_of(row, col, include=True)[source]

Return all coordinates in the square of (col, row) as a list.

Parameters:
  • row (int) – The row of the field.
  • col (int) – The column of the field.
  • include (bool) – Whether or not to include (row, col).
Returns:

list of pairs (row, column) of all fields in

the same square.

Return type:

list of (int, int)

sudokutools.sudoku.surrounding_of(row, col, include=True)[source]

Return all surrounding coordinates of (col, row) as a list.

Parameters:
  • row (int) – The row of the field.
  • col (int) – The column of the field.
  • include (bool) – Whether or not to include (row, col).
Returns:

list of pairs (row, column) of all fields in

the same column, row or square.

Return type:

list of (int, int)

sudokutools.solve - Solving and checking

Low-level solving and checking of sudokus.

Functions defined here:
  • bruteforce(): Solves a sudoku using brute force.
  • calc_candidates(): Calculates candidates of a field in a sudoku.
  • init_candidates(): Sets the candidates for all fields in a sudoku.
  • find_conflicts(): Check sudoku for conflicting fields.
  • is_unique(): Check if a sudoku has exactly one solution.
sudokutools.solve._do_bruteforce(sudoku)[source]

Solve sudoku _inplace_ and yield it in a solved configuration.

This is an internal function and should not be used outside of the solve module.

sudokutools.solve.bruteforce(sudoku)[source]

Solve the sudoku using brute force and yield solutions.

Parameters:sudoku (Sudoku) – The Sudoku instance to solve.
Yields:Sudoku – A solution of the sudoku.
sudokutools.solve.calc_candidates(sudoku, row, col)[source]

Return a set of candidates of the sudoku at (row, col).

Parameters:
  • sudoku (Sudoku) – The Sudoku instance for which the candidates are calculated.
  • row (int) – The row of the field
  • col (int) – The column of the field.
Returns:

A set of candidates for the field at (row, col)

Return type:

set

sudokutools.solve.find_conflicts(sudoku, *coords)[source]

Yield conflicts in sudoku at coords.

If coords is empty all possible coordinates will be searched.

Parameters:
  • sudoku (Sudoku) – The Sudoku instance to check.
  • coords (iterable of (int, int)) – The coordinates to search within.
Yields:

((int, int), (int, int), int)

tuple of coordinate pairs and the

offending value.

E.g.: ((2, 3), (2, 6), 2) indicates, that there is a conflict for the fields (2, 3) and (2, 6) because both of them contain a 2.

sudokutools.solve.init_candidates(sudoku)[source]

Calculate and set all candidates in the sudoku.

Sets all candidates in the sudoku based on the numbers (and nothing else) in the surrounding fields.

Parameters:sudoku (Sudoku) – The Sudoku instance for which the candidates are calculated.
sudokutools.solve.is_unique(sudoku)[source]

Check if sudoku has exactly one solution.

Parameters:sudoku (Sudoku) – The Sudoku instance to check.
Returns:Whether or not the sudoku is unique.
Return type:bool

sudokutools.generate - Creating new sudokus

Create new sudokus.

Functions defined here:
  • create_solution(): Create a complete sudoku without conflicts.
  • generate(): Create a new sudoku.
sudokutools.generate.create_solution()[source]

Returns a sudoku, without empty or conflicting fields.

Returns:The completely filled Sudoku instance.
Return type:Sudoku
sudokutools.generate.generate(min_count=17, symmetry=None)[source]

Generate a sudoku and return it.

Parameters:
  • min_count (int) – Number of fields that must be filled at least. Any number above 81 will raise a ValueError, Any number below 17 makes no sense (but will not cause an error), since unique sudokus must have at least 17 filled fields.
  • symmetry (str) – The kind of symmetry that will be created. Possible values are: None (no symmetry), “rotate-90”, “rotate-180”, “mirror-x”, “mirror-y” and “mirror-xy”.
Returns:

The generated Sudoku instance.

Return type:

Sudoku

Raises:
  • ValueError, if symmetry is not a valid argument.
  • ValueError, if min_count > 81.
sudokutools.generate.generate_from_template(template, tries=100)[source]

Create a new sudoku from a given template.

Parameters:
  • template (Sudoku) – A sudoku, which describes the pattern to use. Every non-zero value of the template will be a filled field in the created solution.
  • tries (int) – The number of tries until we give up. If tries < 0, the function will run, until a solution is found. Take note, that this may deadlock your program, if a solution is not possible.
Returns:

The created sudoku.

Return type:

Sudoku

Raises:

RuntimeError – if the sudoku couldn’t be created, within the given number of tries.

So symmetry isn’t enough for you and you want your sudokus to look like your favorite animal? Then this function is for you! generate_from_template takes the pattern from template and returns a valid sudoku, which matches this pattern (if possible).

Creating sudokus from templates is done in two steps:
  1. Create a template (Sudoku) from the template string.
  2. Hand over this template to this function.

Example for a template string:

111111111
100000001
100000001
100111001
100111001
100111001
100000001
100000001
111111111

Will create a sudoku like this:

1 2 6 | 9 4 8 | 3 7 5
7     |       |     4
3     |       |     6
------+-------+------
9     | 8 1 2 |     3
5     | 3 9 6 |     1
2     | 4 5 7 |     8
------+-------+------
4     |       |     7
8     |       |     2
6 3 7 | 1 2 5 | 4 8 9