改進版的python求解數獨

lt發表於2016-09-23

那個基礎上加入了這個

#py4.py
def force(k):
  global isok
  if isok:  
    return
  if sd[k]==0:
    for m in range(1,10):
     mm = 1
     if m in ex1[k]:
       mm = 0
     else: 
      for n in range(0,9):
        if ((m == sd[k//27*27+(k%9//3)*3+n+n//3*6]) or (m == sd[9*n+k%9]) or (m == sd[k//9*9+n])):
          mm = 0
          break
     if mm:
       sd[k] = m
       if (k == 80):
         isok = 1
         print(sd) #show new sd
         return
       force(k + 1)
    sd[k] = 0
  else:
    if (k == 80):
      isok = 1
      print(sd) #show new sd
      return
    force(k + 1)


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)

isok=0
s="800000000003600000070090200050007000000045700000100030001000068008500010090000400"
sd=list(range(81))
for i in range(81):
  sd[i]=int(s[i])

ex1=dict() #neiber of each cell
for i in range(81):
 ex1[i]=set()
 if sd[i]==0:
  for j in range(81):
   if j!=i and (same_row(i,j) or same_col(i,j) or same_block(i,j)) and sd[j]<>0:
    ex1[i].add(sd[j]) 

print (ex1[1])

force(0)

快了1倍

D:\Python27>\a\timer python py3.py

Timer 3.01  Copyright (c) 2002-2003 Igor Pavlov  2003-07-10
[8, 1, 2, 7, 5, 3, 6, 4, 9, 9, 4, 3, 6, 8, 2, 1, 7, 5, 6, 7, 5, 4, 9, 1, 2, 8, 3, 1, 5, 4, 2, 3, 7, 8, 9, 6, 3, 6, 9, 8, 4, 5, 7, 2, 1, 2, 8, 7, 1, 6,
 9, 5, 3, 4, 5, 2, 1, 9, 7, 4, 3, 6, 8, 4, 3, 8, 5, 2, 6, 9, 1, 7, 7, 9, 6, 3, 1, 8, 4, 5, 2]

Kernel Time  =     0.015 = 00:00:00.015 =   1%
User Time    =     0.936 = 00:00:00.936 =  93%
Process Time =     0.951 = 00:00:00.951 =  95%
Global Time  =     0.999 = 00:00:00.999 = 100%

D:\Python27>\a\timer py4.py

Timer 3.01  Copyright (c) 2002-2003 Igor Pavlov  2003-07-10
set([8, 9, 3, 5, 7])
[8, 1, 2, 7, 5, 3, 6, 4, 9, 9, 4, 3, 6, 8, 2, 1, 7, 5, 6, 7, 5, 4, 9, 1, 2, 8, 3, 1, 5, 4, 2, 3, 7, 8, 9, 6, 3, 6, 9, 8, 4, 5, 7, 2, 1, 2, 8, 7, 1, 6,
 9, 5, 3, 4, 5, 2, 1, 9, 7, 4, 3, 6, 8, 4, 3, 8, 5, 2, 6, 9, 1, 7, 7, 9, 6, 3, 1, 8, 4, 5, 2]

Kernel Time  =     0.015 = 00:00:00.015 =   2%
User Time    =     0.514 = 00:00:00.514 =  86%
Process Time =     0.530 = 00:00:00.530 =  89%
Global Time  =     0.593 = 00:00:00.593 = 100%

相關文章