Shortest Sudoku Solver in Python - How does it work?

前端 未结 5 1696
情话喂你
情话喂你 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:27

    unobfuscating it:

    def r(a):
        i = a.find('0') # returns -1 on fail, index otherwise
        ~i or exit(a) # ~(-1) == 0, anthing else is not 0
                      # thus: if i == -1: exit(a)
        inner_lexp = [ (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)]  # r appears to be a string of 81 
                                            # characters with 0 for empty and 1-9 
                                            # otherwise
        [m in inner_lexp or r(a[:i]+m+a[i+1:]) for m in'%d'%5**18] # recurse
                                # trying all possible digits for that empty field
                                # if m is not in the inner lexp
    
    from sys import *
    r(argv[1]) # thus, a is some string
    

    So, we just need to work out the inner list expression. I know it collects the digits set in the line -- otherwise, the code around it makes no sense. However, I have no real clue how it does that (and Im too tired to work out that binary fancyness right now, sorry)

提交回复
热议问题