数独求解程序(暴力求解)

记录python学习三天后的入门成果:
引用Excel中的数独问题数据,用python进行计算,并将求解结果返回到新的Excel文档中。

import xlrd
data=xlrd.open_workbook(r'c:\users\92801\desktop\sudoku file.xlsx')
table=data.sheet_by_index(0)
a=[table.row_values(i) for i in range(9)]
zset=[]
for i in range(9):
    zset=zset+a[i]
def nset(x):
    rowx=x//9;columnx=x%9;rowmo=rowx//3;columnmo=columnx//3
    b=set([0])|set(a[rowx])|set(a[y][columnx]for y in range(9))|set(a[x1][y1]for x1 in range(rowmo*3,rowmo*3+3) for y1 in range(columnmo*3,columnmo*3+3))
    c=set(x2 for x2 in range(10))-b
    return c
kset=set(i for i in range(81) if zset[i]!=0);zset[0]=nset(0);i=0
while i<81:
    if i in kset:
        a[i//9][i%9]=round(a[i//9][i%9])
        i+=1
        continue
    while zset[i]==set():
        i-=1
        while i in kset:
            i-=1
        a[i//9][i%9]=0;zset[i]=zset[i]-set([min(zset[i])])
    a[i//9][i%9]=min(zset[i])
    for j in range(i+1,81):
        if j in kset:
            continue
        zset[j]=nset(j)
    i+=1
from openpyxl import Workbook
wb = Workbook()
table=wb.create_sheet('result',index=1)
for i in range(9):
    table.append(a[i])
wb.save(r'c:\users\92801\desktop\sudokuresult file.xlsx')


数独求解程序(暴力求解)_第1张图片

你可能感兴趣的:(数独求解程序(暴力求解))