#!/usr/bin/env python # -*- coding: iso-8859-2 -*- """Sudoku solution checker Copyright (C) 2007 Dr. Gergõ ÉRDI http://cactus.rulez.org/ Published under the terms of the GNU General Public License 2.0 $Id: sudoku-check.py,v 1.3 2007-04-06 08:04:40 cactus Exp $ Input should be two files, the template, and the output to verify. Each should contain whitespace-separated symbols, with '0' denoting unspecified fields in the template. """ import sys # A Sudoku board is an n x m hyper-board of boards sized m x n n = m = 3 def encode (row, col): return row * (m * n) + col def decode (i): return (i / (m * n), i % (m * n)) rows = [[encode (i, j) for j in range (0, m * n)] for i in range (0, m * n)] cols = [[encode (i, j) for i in range (0, m * n)] for j in range (0, m * n)] squares = [[encode (row + i, col + j) for i in range (0, m) for j in range (0, n)] for row in range (0, m * n, n) for col in range (0, m * n, m)] def load (filename): f = open_file (filename) contents = f.read ().split() f.close () return contents def open_file (s): if s == "-": return sys.stdin else: return open (s, "r") template = load (sys.argv[1]) output = load (sys.argv[2]) if (len (template) != (m * n) ** 2): raise "Template has wrong length" if (len (output) != (m * n) ** 2): raise "Output to verify has wrong length" for (template_cell, output_cell) in zip (template, output): if template_cell != "0" and template_cell != output_cell: raise "Output doesn't match template" if output_cell == "0": raise "Output to verify has empty cells" for structure in (rows, cols, squares): for region in structure: if len (set([output[i] for i in region])) != n * m: raise "Conflict", map (decode, region)