Search code examples
pythonsudoku

Why does adding 1 print Kill my code (Python)?


I was playing with this sudoku solver, that I found.

Like quoted here it works perfect, but if I uncomment that single print a, that I commented out (line 13), then it stops before finding a full solution...?

import sys
from datetime import datetime # for datetime.now()
 
def same_row(i,j): return (i/9 == j/9)
def same_col(i,j): return (i-j) % 9 == 0
def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)
 
def r(a):
    i = a.find('.')
    if i == -1: # All solved !
        print a
    else:
        #print a
        excluded_numbers = set()
        for j in range(81):
            if same_row(i,j) or same_col(i,j) or same_block(i,j):
                excluded_numbers.add(a[j])        
        for m in '123456789':
            if m not in excluded_numbers:
                # At this point, m is not excluded by any row, column, or block, so let's place it and recurse
                r(a[:i]+m+a[i+1:])
 
if __name__ == '__main__':
    if len(sys.argv) == 2:
        filI = open(sys.argv[1])
        for pusI in filI:
            pusI.strip()
            print "pussle:\n",pusI
            timStart = datetime.now()
            r(pusI) # <- Calling the recursive solver ...
            timEnd = datetime.now()
            print "Duration (h:mm:ss.dddddd): "+str(timEnd-timStart)
    else:
        print str(len(sys.argv)) 
        print 'Usage: python sudoku.py puzzle'

The program needs to be called with a file. That file should hold 1 sudoku per line.

For testing I used this:

25...1........8.6...3...4.1..48.6.9...9.4.8...1..29.4.9.53.7....6..5...7.........

QUESTION:

I can't understand how that single 'print a' manage to break the recursive loop, before it's done. Can anyone give an explanation?

Credit: I originally found the above sudoku solver code here: http://www.scottkirkwood.com/2006/07/shortest-sudoku-solver-in-python.html it's also shown here on StackOverflow: Shortest Sudoku Solver in Python - How does it work?


Solution

  • It actually does find the solution. I ran the program and get the solution

    256491738471238569893765421534876192629143875718529643945387216162954387387612954
    

    If you run with the uncommenting as you suggested and output that to a file:

    python solver.py file.txt > output.txt
    

    And search for the solution string, it is there. It's not the last line, for me it shows up 67% into the file.

    The reason it does this is that the solver basically goes through a ton of combinations and it finds the solution but continues as long as there are any possible paths to go down to find a possible solution.