Lab 06 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', end=" "), else: print('-', end=" "), print('\n') print('\n') def moves(self): """Return a list of possible moves given the current placements.""" moves=[] for i in self.queens: tup=[] if self.queens[i]+1 in range(0,8): tup.append(self.queens(i)+1,i) if self.queens[i]-1 in range(0,8): tup.append(self.queens[i]-1,i) moves.append(tup) return moves def LineCountQueen(self,r): nr = 0 for i in range(len(self.queens)): if self.queens[i] == r: nr+=1 return nr def DiagCountQueen(self,c): nr = 0 for i in range(len(self.queens)): Row = abs(self.queens[c]-self.queens[i]) Col = abs(c-i) if(Col==Row): nr+=1 if nr>0: return int(nr-1) return 0 def neighbor(self,move): self.queens[0]=move[0] def cost(self): nr = 0 for i in range(len(self.queens)): nr+=self.LineCountQueen(self.queens[i]) for i in range(len(self.queens)): nr+=self.DiagCountQueen(i) return nr 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.""" # YOU FILL THIS IN def main(): """Create a problem, solve it with simulated anealing, and console-animate.""" print("Enter the number of queens") n = 8 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()