2013-06-05 1 views
1

저는 Sudoku puzzle solver를 작성하려 했었고, 지금까지 퍼즐을 표시하려고 노력했습니다. 여기 내 코드는 지금까지입니다 : 나는 그것을 인쇄하려고 할 때Python sudoku puzzle solver가 정확하게 퍼즐을 표시하지 않습니다.

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 

, 나는 파이프의 두 개의 수직선을 얻을 :

여기에 세포이며,
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 

그리드에 대한 코드입니다 (|). 누군가 내가 뭘 잘못하고 있다고 말할 수 있습니까? 이 파일 수익률 이상도 잘못

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

순회입니다

if 1 <= number <= 9: 

+0

그러나 각 번호 사이에 두 개의 파이프가 있습니다. '템플릿'은 무엇입니까? – kirelagin

+0

일부 출력물을 보여 주시겠습니까? – kirelagin

+0

당신이 _need_ mangling을하지 않는 한, 모든것 앞에서'__'을 사용하지 마십시오. –

답변

0

코드를 읽기가 정말 어렵습니다. 문제를 하위 문제로 분리하고보다 논리적으로 구조화해야합니다.

그러나 직접 질문에 대답하려면 7 행에서 빈 템플릿을 self.__template에 할당하십시오. 14 번째 줄에서는 템플릿을 문자 목록으로 변환하고 (이유는 무엇입니까?) 결국 문자를 쓰지 않고 self.__template_list에 할당합니다. 마지막으로 21-23 줄에서 템플릿 문자 목록 (아직 비어 있음)을 반복하고 self.__answer에 추가합니다. __str__()에 인쇄합니다. 따라서 당신은 파이프 만 가져옵니다. 의 대부분을 염려하지 말아야 따라서

  1. 그리드의 텍스트 표현이 그리드의 일반적인 개념과 무관해야하며, 어떻게 코드를 개선에 관한

    어쩌면 내가 당신에게 몇 가지 힌트를 줄 수 Grid 클래스의 메소드. 귀하의 경우에는 __init__() 메서드가 쓰러져서 실제로 메서드가 무엇을하는지 이해하기가 어렵습니다. 그리드가 끝까지 표시되는 방법을 알 필요가없는 여러 작업을 그리드와 함께 수행 할 수 있습니다.

    그리드를 출력하는 코드는 귀하의 사례 인 __str__()에서 그 책임을지는 방법에 완전히 국한되어야합니다.

  2. 다른 방법이나 클래스 사용자와 관련이없는 변수의 경우 멤버 변수 대신 로컬 변수를 사용하십시오. 불필요한 멤버 변수는 예를 들어 dir()을 사용하여 인스턴스 멤버를 검사 할 때 디버깅 할 때 코드를 이해하기 어렵고 효율적이지 않으며 혼란스럽게 만듭니다.

  3. 그리드를보다 논리적으로 표현하는 데이터 구조를 생각해보십시오 (그리고 필요한 데이터 만 포함하고 표현을위한 불필요한 세부 정보는 포함하지 않습니다). 목록 목록을 제안합니다. 파이썬에서 매우 조작하기 쉽기 때문입니다 (예를 들어 2 차원 배열을 사용할 수도 있습니다).이 버전은 매우 엄격한 형식 (NO 구분 선 또는 문자, 줄에 문자의 정확한 수)을 가진 파일을 기대하는

    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입니다. 다른 모든 변수는 각 함수에 대해 로컬입니다.

2

이 잘못 (항상있을 것 참)

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

사용 라인없는 자 .

작은 부분에 코드를 작성하고 테스트 해 보시기 바랍니다. print을 넣어 코드가 예상 한대로 작동하는지 확인하십시오.

+0

또는 정수 값을 찾는 지 확인하려면'if number in range (1, 10)'을 사용하십시오. – tamasgal

관련 문제