1

我试图写一个数独解谜器,到目前为止,我一直在试图让它显示谜题。到目前为止,这是我的代码:

class Cell:
'''A cell for the soduku game.'''
def __init__(self):
    #This is our constructor
    self.__done = False #We are not finished at the start
    self.__answer = (1,2,3,4,5,6,7,8,9) #Here is the tuple containing all of our possibilities
    self.__setnum = 8 #This will be used later when we set the number.
def __str__(self):
    '''This formats what the cell returns.'''
    answer = 'This cell can be: '
    answer += str(self.__answer) #This pulls our answer from our tuple
    return answer
def get_possible(self):
    '''This tells us what our possibilities exist.'''
    answer = ()
    return self.__answer
def is_done(self):
    '''Does a simple check on a variable to determine if we are done.'''
    return self.__done
def remove(self, number):
    '''Removes a possibility from the possibility tuple.'''
    if number == 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9: #Checks if we have a valid answer
        temp = list(self.__answer) #Here is the secret: We change the tuple to a list, which we can easily modify, and than turn it back.
        temp.remove(number)
        self.__answer = tuple(temp)
def set_number(self, number):
    '''Removes all but one possibility from the possibility tuple. Also sets "__done" to true.'''
    answer = 8
    for num in self.__answer:
        if num == number:
            answer = number #Checks if the number is in the tuple, and than sets that value as the tuple, which becomes an integer.
    self.__answer = answer
    self.__done = True
    return self.__answer

这是针对单元格的,这里是网格的代码:

class Grid:
'''The grid for the soduku game.'''
def __init__(self, puzzle):
    '''Constructs the soduku puzzle from the file.'''
    self.__file = open(puzzle)
    self.__puzzle = ''
    self.__template = '   |   |   \n   |   |   \n   |   |   \n   |   |   \n   |   |   \n   |   |   \n   |   |   \n   |   |   \n   |   |   \n'
    for char in self.__file:
        if char == '.':
            self.__puzzle += ' '
        else:
            self.__puzzle += char
    count = 0
    self.__template_list = list(self.__template)
    for char in self.__puzzle:
        if char != '|':
            if char == '.' or ' ':
                self.__template_list[count] = ' '
            else:
                self.__template_list[count] = char
    self.__answer = ''
    for char in self.__template_list:
        self.__answer += char
    self.__file.close()
def __str__(self):
    '''Prints the soduku puzzle nicely.'''
    return self.__answer

当我尝试打印它时,我得到两条垂直的管道 (|)。有人可以告诉我我做错了什么吗?

4

2 回答 2

2

这是错误的(它永远是真的)

if number == 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9:

利用

if 1 <= number <= 9:

这也是错误的

for char in self.__file:
    if char == '.':
        self.__puzzle += ' '
    else:
        self.__puzzle += char

遍历文件会产生而不是字符。

我建议您以较小的部分编写和测试您的代码。在其中放置一些prints 以确保代码正在执行您期望的操作。

于 2013-06-05T07:37:17.410 回答
0

你的代码真的很难阅读。你应该把你的问题分成子问题,并更有逻辑地组织它们。

但是要直接回答您的问题,在第 7 行中,您将一个空模板分配给self.__template. 在第 14 行中,您将模板转换为字符列表(为什么?毕竟您没有写入它)并将其分配给self.__template_list. 最后,在第 21 到 23 行中,您将遍历模板字符列表(仍然为空)并将其附加到self.__answer您打印的__str__(). 因此,您得到的只是管道。

也许我可以给你一些关于如何改进代码的提示:

  1. 网格的文本表示应该与网格的一般概念无关,因此不应该涉及 Grid 类的大多数方法。在您的情况下,它乱扔了该__init__()方法,并且很难理解该方法的实际作用。您可以对您的网格执行多项操作,而无需知道网格最终是如何显示的(如果有的话)。

    在您的情况下,输出网格的代码应完全限制在负责该方法的方法中__str__()

  2. 对于与其他方法或类的用户无关的变量,请使用局部变量而不是成员变量。不必要的成员变量会使您的代码更难理解,效率更低,并且在调试时使您感到困惑,例如在检查实例成员时dir()

  3. 考虑一个更合乎逻辑地表示您的网格的数据结构(并且只包含必要的数据,而不是表示的多余细节)。我建议列出一个列表,因为这在 python 中很容易操作(例如,您也可以使用二维 numpy 数组)。

我建议类似这样的东西:

class Grid:
    '''The grid for the soduku game.'''

    def __init__(self, puzzle):
        '''Constructs the soduku puzzle from the file.'''

        self.grid = []

        with open(puzzle, "r") as f:
            for line in f:
                # strip CR/LF, replace . by space, make a list of chars
                self.grid.append([" " if char in " ." else char for char in line.rstrip("\r\n")])

    def __str__(self):
        '''Prints the soduku puzzle nicely.'''

        lines = []

        for i, row in enumerate(self.grid):
            if i != 0 and i % 3 == 0:
                # add a separator every 3 lines
                lines.append("+".join(["-" * 3] * 3))

            # add a separator every 3 chars
            line = "|".join(map("".join, zip(*([iter(row)] * 3))))
            lines.append(line)

        lines.append("")

        return "\n".join(lines)

请注意,此版本需要一个格式非常严格的文件(没有分隔线或字符,每行字符的确切数量)。您可以练习改进它以阅读更自由的格式。

另请注意,我使用的唯一成员变量是self.grid. 所有其他变量都是各自函数的局部变量。

于 2013-06-05T08:45:57.233 回答