sudoku solver in Python ...

pataphor pataphor at
Thu Jan 24 23:17:54 CET 2008

On Thu, 24 Jan 2008 21:09:42 +0100
Thomas Thiel <thomas.thiel13 at> wrote:

> Neither fast nor user friendly, but very concise:

This is a bit faster:

options = set([str(i) for i in range(1, 10)])

def allow(puzzle,i):
    exclude = set(x if i//9 == j//9 or i%9 == j%9 
        or i//27 == j//27 and (i%9)//3 == (j%9)//3 
        else '0' for j,x in enumerate(puzzle))
    return options-exclude

def solve(puzzle):
    zeros = [i for i,x in enumerate(puzzle) if x  == '0']
    if not zeros:
        print puzzle
        i,R = min(((j,allow(puzzle,j)) for j in zeros),
            key=lambda x: len(x[1]))
        for option in R:
            solve(puzzle[:i] + option + puzzle[i+1:])


More information about the Python-list mailing list