我当时正试图写一个数独解谜器,到目前为止,我一直在试图让它显示这个谜题。以下是我目前为止的代码:
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
这是针对单元格的,下面是网格的代码:
^{pr2}$当我试图打印它时,我得到两条垂直的管道(|)。有人能告诉我我做错了什么吗?在
你的代码真的很难读。你应该把你的问题分解成子问题,并使它们更有逻辑性。在
但是为了直接回答您的问题,在第7行中,您为
self.__template
分配了一个空模板。在第14行中,将模板转换为字符列表(为什么?毕竟你没有给它写信)并把它赋给self.__template_list
。最后,在第21到23行中,您将迭代模板字符列表(仍然是空的),并将其附加到self.__answer
,在__str__()
中打印。这样你就得到了管道。在也许我可以给你一些关于如何改进代码的提示:
网格的文本表示应该与网格的一般概念无关,因此不应该涉及网格类的大多数方法。在您的例子中,它丢弃了
__init__()
方法,这使您很难理解该方法实际做了什么。您可以对网格执行一些操作,这些操作不需要知道网格最后是如何显示的(如果有的话)。在输出网格的代码应该完全局限于负责这个的方法,在您的例子中
__str__()
。对于与其他方法或类的用户无关的变量,请使用局部变量而不是成员变量。不必要的成员变量会使代码更难理解、效率更低,并且在调试时会使您感到困惑,例如,在使用
dir()
检查实例成员时。设想一个更符合逻辑地表示网格的数据结构(它只包含必要的数据,而不包含表示的多余细节)。我建议使用列表列表,因为这在python中非常容易操作(例如,您也可以使用二维numpy数组)。
我建议类似的建议:
注意,这个版本需要一个格式非常严格的文件(没有分隔线或字符,每行的确切字符数)。你可以练习改进它来阅读更自由的格式。在
还要注意,我使用的唯一成员变量是
self.grid
。所有其他变量都是各自函数的局部变量。在这是错误的(永远是真的)
使用
^{pr2}$这也是错误的
迭代一个文件会产生行而不是字符。在
我建议你用较小的部分编写和测试代码。在其中放入一些
print
,以确保代码按照您的预期运行。在相关问题 更多 >
编程相关推荐