2017-04-02 9 views
0

len을 사용하여 온도를 추가하려고하면 Object 클래스의 보드 객체가 오류를 던지기는하지만 n-queens 문제를 다시 작성하여 시뮬레이션 어닐링으로 해결하려고합니다. 보드) ** 2. 어떤 도움을 주시면 감사하겠습니다 !! 나는 소스 코드와 출력을 포함시켰다. 감사!N-Queens 어닐링 프로그램이 작동하지 않습니다.

import time 
import random 
import math 

class Board(object): 
    """An N-queens solution attempt.""" 

    def __init__(self, queens): 
     """Instances differ by their queen placements.""" 
     self.queens = queens.copy() 

    def display(self): 
     """Print the board.""" 
     for r in range(len(self.queens)): 
      for c in range(len(self.queens)): 
       if self.queens[c] == r: 
        print 'Q', 
       else: 
        print '-', 
      print 
     print 

    def moves(self): 
     """Return a list of possible moves given the current placements.""" 
     bestMoves = [] 
     optimalHeuristic = heuristic(board) 
     for a, b in moves.iteritems(): 
      if b < optimalHeuristic: 
       optimalHeuristic = b 

     for a, b in moves.iteritems(): 
      if b == optimalHeuristic: 
       bestMoves.append(a) 

     return bestMoves 

    def neighbor(self, move): 
     """Return a Board instance like this one but with one move made.""" 
     if len(bestMoves) > 0: 
      pick = random.randint(0, len(bestMoves) - 1) 
      column = bestMoves[pick][0] 
      row = bestMoves[pick][1] 
      board[column] = row 
     return board 

    def heuristic(self): 
     """Compute the cost of this solution.""" 
     h = 0 
     ##checking columns 
     for i in range(1, n): 
      ##checking rows 
      for j in range(i+1, n): 
       if board[i] == board[j]: 
        h += 1 
       x = j - i 
       ##checking the diagonals 
       if board[i] == board[j] - x or board[i] == board[j] + x: 
        h += 1 
     return h 

class Agent(object): 
    """Knows how to solve an n-queens problem with simulated annealing.""" 

    def anneal(self, board): 
     """Return a list of moves to adjust queen placements.""" 
     temperature = len(board)**2 
     annealRate = 0.95 
     newHeuristic = heuristic(board) 

     while newHeuristic > 0: 
      board = makeMove(board, newHeuristic, temperature) 
      newHeuristic = heuristic(board) 
      newTemperature = max(temperature * annealRate, 0.01) 
      temperature = newTemperature 
      ##steps cap is here to avoid the algorithm getting stuck 
      if steps >= 10000: 
       break 

     boardCopy = list(board) 
     foundMove = False 

     while not foundMove: 
      boardCopy = list(board) 
      newRow = random.randint(0, len(board)-1) 
      newColumn = random.randint(0, len(board)-1) 
      boardCopy[newColumn] = newRow 
      newHeuristic = heuristic(boardCopy) 
      if newHeuristic < optimalHeuristic: 
       foundMove = True 
      else: 
       delta_e = optimalHeuristic - newHeuristic 
       ##aceptance prob equation min(1, e**(delta e/temp)) 
       acceptProbability = min(1, math.exp(delta_e/temperature)) 
       foundMove = random.random() <= acceptProbability 
     return boardCopy 

def main(): 
    """Create a problem, solve it with simulated anealing, and console-animate.""" 
    print("Enter the number of queens") 
    n = input() 
    queens = dict() 
    for column in range(n): 
     row = random.choice(range(n)) 
     queens[column] = row 

    board = Board(queens) 
    board.display() 

    agent = Agent() 
    path = agent.anneal(board) 

    while path: 
     move = path.pop(0) 
     board = board.neighbor(move) 
     time.sleep(0.1) 
     board.display() 

if __name__ == '__main__': 
    main() 

Output: 


Enter the number of queens 
8 
- - - - - - Q - 
- - - - - Q - - 
- - - - - - - Q 
- - - - - - - - 
- Q - - - - - - 
- - - Q Q - - - 
- - - - - - - - 
Q - Q - - - - - 


Traceback (most recent call last): 
    File "F:\Intelligent Systems\annealingnqueens.py", line 119, in <module> 
    main() 
    File "F:\Intelligent Systems\annealingnqueens.py", line 110, in main 
    path = agent.anneal(board) 
    File "F:\Intelligent Systems\annealingnqueens.py", line 66, in anneal 
    temperature = len(board)**2 
TypeError: object of type 'Board' has no len() 
+0

'agent.anneal (보드)의 예상 출력은 무엇인가 '또는 무엇'이'렌 (보드)의 실제 좌변 기대하고있다? –

+0

필자는 len (board)이 기본적으로 보드의 값을 제공하여 온도에 대한 부동 소수점 숫자를 얻길 원합니다. agent.anneal (보드)은 지정된 보드 객체에 어닐링 기능을 적용하고 해결책을 제공한다고 가정합니다. – user7803707

답변

0

당신은 그렇지 len(board)에 대한 호출이 정의되지 않습니다, 당신의 보드 클래스의 __len__ 방법을 정의 할 필요가있다. 이 외에도 여러 가지 특수 이중 밑줄 메서드는 the Python 3 documentation (또는 선호하는 경우 the Python 2 documentation)에 나와 있습니다. 여왕의 길이가 수량이 원하는 것을 가정하면 :

class Board(object): 
"""An N-queens solution attempt.""" 

def __init__(self, queens): 
    """Instances differ by their queen placements.""" 
    self.queens = queens.copy() 

def __len__(self): 
    return len(self.queens)