Python:添加1个打印会杀死我的代码?

Mar*_*tin 1 python sudoku

我正在玩这个数独求解器,我找到了.

就像这里所引用的一样,它很完美,但是如果我取消注释那个print a,我注释掉了(第13行),那么它在找到完整的解决方案之前就会停止......?

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'
Run Code Online (Sandbox Code Playgroud)

需要使用文件调用该程序.该文件应该每行持有1个数独.

为了测试我使用了这个:

25...1........8.6...3...4.1..48.6.9...9.4.8...1..29.4.9.53.7....6..5...7.........
Run Code Online (Sandbox Code Playgroud)

题:

在完成之前,我无法理解单个'print a'如何设法打破递归循环.任何人都可以解释一下吗?

最好的问候Martin@Hvidberg.net

信用:我最初在这里找到了上面的数独求解器代码:http: //www.scottkirkwood.com/2006/07/shortest-sudoku-solver-in-python.html 它也显示在StackOverflow上: Python中最短的数独求解器 -它是如何工作的?

ric*_*hsu 5

它确实找到了解决方案.我运行程序并获得解决方案

256491738471238569893765421534876192629143875718529643945387216162954387387612954
Run Code Online (Sandbox Code Playgroud)

如果您按照建议运行取消注释并将其输出到文件:

python solver.py file.txt > output.txt
Run Code Online (Sandbox Code Playgroud)

并搜索解决方案字符串,它就在那里.这不是最后一行,对我来说,它显示67%的文件.

这样做的原因是解算器基本上经历了大量的组合并且它找到了解决方案,但只要有任何可能的路径下去找到可能的解决方案,它就会继续.