Skip to content

Instantly share code, notes, and snippets.

@aksiksi
Created December 27, 2011 21:45
Show Gist options
  • Save aksiksi/1525260 to your computer and use it in GitHub Desktop.
Save aksiksi/1525260 to your computer and use it in GitHub Desktop.
Sudoku grid slicer
# Written by: Assil Ksiksi
# Date: Decemeber 28th, 2011
# A simple script that "slices" a Sudoku grid into 9 3x3 boxes. A similar method
# may be included in my Sudoku solver to determine whether or not a number can
# be placed in a certain cell. Should also be applicable to rows and columns.
from random import seed, choice
def create_grid():
''' Randomly generates a 9x9 multi-dimensional "pseudo-Sudoku grid" in list format. '''
grid = []
choices = '123456789............'
for i in range(9):
row = []
for j in range(9):
seed(None)
row.append(choice(choices))
grid.append(row)
return grid
def format_box(box, count):
''' Formats each box from a 9x9 Sudoku grid and adds a box #. '''
new = []
new.append('Box #{}'.format(count) + '\n')
for i in box:
for j in i:
new.append(j + ' ')
new.append('\n')
return ''.join(new)
def slice_grid():
''' Splices a 9x9 Sudoku grid, and prints out the boxes that form it.
Runtime: ~0.035s'''
grid = create_grid()
boxes = []
row = 3 # Used to determine where slicing should occur.
col = 3
count = 1
for i in range(3): # Used to keep count of row number
for j in range(3): # Creates boxes for each row
boxes.append([x[col-3:col] for x in grid[row-3:row]]) # Nifty list comprehension that splices a multi-dimensional list.
col += 3
for k in boxes: # Sifts through boxes in each row, and passes them to format_box
print format_box(k, count)
count += 1
boxes = []
col = 3
row += 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment