PySwipPySwip
Home
What's New?
Community
Documentation
Source
Home
What's New?
Community
Documentation
Source
  • What's New in v0.3.2

What's New in v0.3.2

See the full list of changes at v0.3.2 Release Notes.

Python to Prolog Value Transfer Using String Interpolation

See the documentation on String Interpolation from Python to Prolog.

Introducing the Examples Package

The new pyswip.examples package enables using some of the PySwip examples in code and the command line.

pyswip.examples.sudoku

The pyswip.examples.sudoku module provides the Matrix class which holds a 9x9 Sudoku puzzle. You can create a Matrix instance from a list-of-lists. Items in that list should be integers in the range [0-9] where 0 represents a blank column:

from pyswip.examples.sudoku import Matrix

data = [
    [0, 6, 0, 1, 0, 4, 0, 5, 0],
    [0, 0, 8, 3, 0, 5, 6, 0, 0],
    [2, 0, 0, 0, 0, 0, 0, 0, 1],
    [8, 0, 0, 4, 0, 7, 0, 0, 6],
    [0, 0, 6, 0, 0, 0, 3, 0, 0],
    [7, 0, 0, 9, 0, 1, 0, 0, 4],
    [5, 0, 0, 0, 0, 0, 0, 0, 2],
    [0, 0, 7, 2, 0, 6, 9, 0, 0],
    [0, 4, 0, 5, 0, 8, 0, 7, 0],
]
puzzle = Matrix(data)

Alternatively, a Matrix instance can be created from a string. In this case, dot (.) character represents a blank spot:

from pyswip.examples.sudoku import Matrix

text = """
. 6 . 1 . 4 . 5 .
. . 8 3 . 5 6 . .
2 . . . . . . . 1
8 . . 4 . 7 . . 6
. . 6 . . . 3 . .
7 . . 9 . 1 . . 4
5 . . . . . . . 2
. . 7 2 . 6 9 . .
. 4 . 5 . 8 . 7 .
"""
puzzle = Matrix.from_text(text)

Once a Matrix instance is created, you can solve it using the solve function (surprise!). It will return a solution Matrix if there's a solution, otherwise False:

from pyswip.examples.sudoku import solve

solution = solve(puzzle)
if solution:
    print(solution)
else:
    print("There's no solution")

You can retrieve the Prolog source that solves the puzzle using the prolog_source function:

from pyswip.examples.sudoku import prolog_source

source = prolog_source()
print(source)

A sample puzzle is returned using sample_puzzle function:

from pyswip.examples.sudoku import sample_puzzle

puzzle = sample_puzzle()
print(puzzle)
Last Updated:
Contributors: Yuce Tekol