Fix squares; add dimension property; add some tests

This commit is contained in:
Eryn Wells 2017-10-08 07:23:03 -07:00
parent f98a0f4f75
commit 01428e3972
2 changed files with 69 additions and 5 deletions

View file

@ -12,10 +12,14 @@ class Sudoku:
dim = math.sqrt(size)
if dim != int(dim):
raise ValueError('Board size must have an integral square root.')
self.dimension = int(dim)
self._dimension = int(dim)
self.size = size
self.board = bytearray(b'\x00' * (size * size))
@property
def dimension(self):
return self._dimension
@property
def rows(self):
sz = self.size
@ -27,6 +31,11 @@ class Sudoku:
sz2 = sz ** 2
return [range(i, sz2, sz) for i in range(sz)]
@property
def squares(self):
dim = self.dimension
return [self.square(x, y) for y in range(dim) for x in range(dim)]
@property
def solved(self):
def _check_group(group):
@ -40,14 +49,16 @@ class Sudoku:
# TODO: WIP
def square(self, x, y):
dim = int(math.sqrt(self.size))
dim = self.dimension
if (x < 0 or x >= dim) or (y < 0 or y >= dim):
raise IndexError('Invalid coordinates for square: ({}, {})'.format(x, y))
offset_x = x * dim
offset_y = y * dim
offset = (x * dim, y * dim * self.size)
def _range(i):
start = offset_x + i * self.size
start = (offset[1] + i * self.size) + offset[0]
return range(start, start + dim)
ranges = itertools.chain(*[_range(i) for i in range(dim)])
return ranges

53
test.py Normal file
View file

@ -0,0 +1,53 @@
#!env python3
# Eryn Wells <eryn@erynwells.me>
'''
Unit tests for the Sudoku module.
'''
import unittest
import sudoku
class Sudoku4Tests(unittest.TestCase):
def setUp(self):
self.board = sudoku.Sudoku(size=4)
def test_that_board_is_sane(self):
self.assertEqual(self.board.size, 4)
self.assertEqual(len(self.board.board), 4**2)
self.assertEqual(self.board.dimension, 2)
def test_rows(self):
expected_rows = [
[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]
]
for (row, exrow) in zip(self.board.rows, expected_rows):
row_list = list(row)
with self.subTest(row=row_list, ex=exrow):
self.assertEqual(row_list, exrow)
def test_columns(self):
expected_columns = [
[0, 4, 8, 12],
[1, 5, 9, 13],
[2, 6, 10, 14],
[3, 7, 11, 15]
]
for (col, excol) in zip(self.board.columns, expected_columns):
col_list = list(col)
with self.subTest(col=col_list, ex=excol):
self.assertEqual(col_list, excol)
def test_squares(self):
expected_squares = [
[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 12, 13],
[10, 11, 14, 15]
]
for (sq, exsq) in zip(self.board.squares, expected_squares):
sq_list = list(sq)
with self.subTest(sq=sq_list, ex=exsq):
self.assertEqual(sq_list, exsq)