我如何获得一个解决数独难题的计数器?(python)

时间:2014-12-30 04:40:27

标签: python counter sudoku

import os
from collections import counter

cwd = os.getcwd()
filename1 = cwd + "/sudoku1.txt"

grid1 = []
with open(filename1) as f:
    for line in f:
        grid1.append([int(i) for i in line.split()])


cwd = os.getcwd()

filename2 = cwd + "/sudoku2.txt"

grid2 = []
with open(filename2) as f:
    for line in f:
        grid2.append([int(i) for i in line.split()])

cwd = os.getcwd()

filename3 = cwd + "/sudoku3.txt"

grid3 = []
with open(filename3) as f:
    for line in f:
        grid3.append([int(i) for i in line.split()])




def allDifferent1D(l):
    for i in l:
        if i != 0:
            if l.count(i)>1:                    
                return False
    return True

def allDifferent2D(l):
    for row in l:
        if not allDifferent1D(row):
            return False
    for c in range(len(l)):
        col = []
        for r in range(len(l)):
            col.append(l[r][c])
        if not allDifferent1D(col):
            return False
    return True


def checkAll3By3s(grid):
    for i in [0,3,6]:
        for j in [0,3,6]:
            subGrid = [grid[i][j:j+3]]
            subGrid.append(grid[i+1][j:j+3])
            subGrid.append(grid[i+2][j:j+3])
            if not check3By3(subGrid):
                return False
    return True

def check3By3(grid):
    contains = dict()
    for i in range(0,10):
        contains[i] = False
    for i in range(3):
        for j in range(3):
            if contains[grid[i][j]]:
                return False
            else:
                contains[grid[i][j]] = True
    return True

def isValidSudoku(grid):
    # Check all rows and columns
    if (not allDifferent2D(grid)):
        return False
    if (not checkAll3By3s(grid)):
        return False

    return True

def complete(grid):
#checks the grid for any zeros or negatives. Takes priority over the sudoku checking aspect as it is implied to be invalid
    for i in range(len(grid)):
        for j in range(len(grid[i])):
            if grid[i][j]<=0:
                return False
    if (not allDifferent2D(grid)):
        return False
    if (not checkAll3By3s(grid)):
        return False


    return True



def compatableValue(grid,k):
    # creates a dictionary for each row/column that, for the purpose of this function, takes k and compares it with other values in the row/column, giving it a value of 1 if it is unique for the grid[i][j] value solveSudoku is iterating over 
    for i in range(len(grid)):
                seenValues=dict()
                for j in range(len(grid[i])):
                    a=collections.counter(grid[i][j])

                    if k != 0 and k in seenValues:
                        return False

                seenValues[k] += 1
                return seenValues[k]

def solveSudoku(grid):
#if the grid isnt a sudoku solution, the function sets out to fill in blank spaces(as pre filled in spots are the conditions for the grid and thus necessary

    if complete(grid)==True:
        return(grid)

    for i in range(0,9):
        for j in range(0,9):
            #only proceeds to change a value if it is zero. Calls compatableValue to see if each prospective value has been used
            if grid[i][j]==0:
                for k in range(1,10):
                    if compatableValue(grid,k)==1:
                        grid[i][j]=k
                        print(grid)
                    result=solveSudoku(grid)
                    if result != False:
                        solveSudoku(grid)
                #changes values back to zero for next attempt at solving the problem
                grid[i][j]=0
                return False
    return True




print(solveSudoku(grid2))

我正在尝试解决数字拼图,其中空格用零表示,并根据计数器是否已在行/列/ 3by3网格中找到它们来填充它们。我使用python 3.4.1并且计数器不起作用。我不知道我做错了什么。

2 个答案:

答案 0 :(得分:1)

您的import是:

from collections import counter

但您尝试使用collections.counter代替。您从未导入collections,因此这将是NameError例外。要解决此问题,请将import更改为

import collections

此外,正如@DSM在评论中提到的那样,Counter必须拼写为大写C

我相信你在那个冗长的,极其重复的代码中还有很多其他的错误,例如你试图a=collections.counter(grid[i][j]) - counter调用一个数字是没有意义的(并且会失败),然后你忽略了a,我相信。

但是每个问题的错误数量应该很少,所以通过修复一个错误,我认为我现在已经完成了我的工作: - )

答案 1 :(得分:1)

来自python docs:

c = Counter()                           # a new, empty counter
c = Counter('gallahad')                 # a new counter from an iterable
c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
c = Counter(cats=4, dogs=8)             # a new counter from keyword args

Counter()返回一个计数器对象,您可以将其传递给任何内容,可迭代,映射或多个命名数量。计数器对象背后的想法是它将计算向其添加值的次数。比如说,如果我想把碗里的水果算在内,我可以这样做:

bowl = Counter()
bowl['banana'] = 3
bowl['banana'] += 4

现在,在您的代码中,您似乎将单个数独单元格的内容传递给Counter的构造函数。我不确定你要对这个柜台做些什么,但我认为你首先不需要一个。创建失败后,你甚至都没有使用计数器。而且我不明白看到的值是什么用于。也许你应该先尝试用英语写下你想要做的事情,这样我们才能理解你想要达到的目标。