Shortest Sudoku Solver in Python - How does it work?

前端 未结 5 1686
情话喂你
情话喂你 2020-12-04 05:04

I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:

def r(a):i=a.find(\'0\');~i         


        
5条回答
  •  攒了一身酷
    2020-12-04 05:31

    r(a) is a recursive function which attempts to fill in a 0 in the board in each step.

    i=a.find('0');~i or exit(a) is the on-success termination. If no more 0 values exist in the board, we're done.

    m is the current value we will try to fill the 0 with.

    m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] evaluates to truthy if it is obivously incorrect to put m in the current 0. Let's nickname it "is_bad". This is the most tricky bit. :)

    is_bad or r(a[:i]+m+a[i+1:] is a conditional recursive step. It will recursively try to evaluate the next 0 in the board iff the current solution candidate appears to be sane.

    for m in '%d'%5**18 enumerates all the numbers from 1 to 9 (inefficiently).

提交回复
热议问题