HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Checking for legal sudoku boards

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkingboardslegalforsudoku

Problem

My problem statement is:


Write a function to indicate if a given Sudoku board is legal. This function takes a Sudoku board (which you may assume is a N2xN2 2d list of integers, where N is an integer), and returns True if the board is legal, as described above.

And here's my solution:

```
import time, random

def solve_all(grids, name='', showif=0.0):
"""Attempt to solve a sequence of grids. Report results.
When showif is a number of seconds, display puzzles that take longer.
When showif is None, don't display any puzzles."""
def time_solve(grid):
start = time.clock()
values = solve(grid)
t = time.clock()-start
## Display puzzles that take long enough
if showif is not None and t > showif:
display(grid_values(grid))
if values: display(values)
print '(%.2f seconds)\n' % t
return (t, solved(values))
times, results = zip(*[time_solve(grid) for grid in grids])
N = len(grids)
if N > 1:
print "Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max %.2f secs)." % (
sum(results), N, name, sum(times)/N, N/sum(times), max(times))

def solved(values):
"A puzzle is solved if each unit is a permutation of the digits 1 to 9."
def unitsolved(unit): return set(values[s] for s in unit) == set(digits)
return values is not False and all(unitsolved(unit) for unit in unitlist)

def from_file(filename, sep='\n'):
"Parse a file into a list of strings, separated by sep."
return file(filename).read().strip().split(sep)

def random_puzzle(N=17):
"""Make a random puzzle with N or more assignments. Restart on contradictions.
Note the resulting puzzle is not guaranteed to be solvable, but empirically
about 99.8% of them are solvable. Some have multiple solutions."""
values = dict((s, digits) for s in squares)
for s in shuffled(squares):
if not assign(values, s, random.choice(values[s])):
break

Solution

Coding style

Please follow PEP8, the style guide for Python code.
As you read through it, you should recognize several coding style violations in your posted code.
There is also a command line tool called pep8, which can check your entire project and report the violations. You can install it with:

pip install pep8


Strange condition

This looks very strange:

return values is not False and all(unitsolved(unit) for unit in unitlist)


From the posted code it's not clear what is the type of values.
The plural name implies some kind of collection,
but then it can never be False.
As such, this condition doesn't make sense.

Code Snippets

pip install pep8
return values is not False and all(unitsolved(unit) for unit in unitlist)

Context

StackExchange Code Review Q#97141, answer score: 3

Revisions (0)

No revisions yet.