python 女王银奖

NQueens Slver in python

我正在制作一个 nQueen 问题求解器,但每次我 运行 程序都会启动此错误:

"tuple" 没有属性 "row"

我想知道函数位置是否结构良好,因为是抛出错误的地方

import sys #use of argv

#Create the object queen with the row and column
class Queen:
    def __init__(self, row, col):
        self.row = row
        self.col = col

    def __repr__(self):
        return "Row: "+ str(self.row) + " Column: " + str(self.col)

#Validate if I can place the Queen in that space, return false or true
def place(Board,row,col):
    for i in range(0,len(Board)-1):
        #Attack conditions: cant place in the same column, row and diagonal
        if (Board[i].row == row) or (Board[i].col == col) or (abs(Board[i].row - row) == abs(Board[i].col - col)):
            return False
    return True

#Recursive function that Append the queen to the board if it can be place
def NQueens(Board,n,row):
    for i in range(1,n):
        #if the row is > than n the fuction will return the list 
        if (row > n):
            return Board 
        #If it can be place we call the NQueens function with the next row
        elif place(Board,row,i):
            Queenaux = (row,i)
            Board.append(Queenaux)
            NQueens(Board,n,row+1)

#The user enter the number of queens and size of the board
n = int(sys.argv[1])
print("nQueens Problem Solver")
print("Chess Board: ",n,"x",n)
print("Number Queens:",n)
#Create the list Board
Board = []
#Start the NQueens function with row=1
Board = NQueens(Board,n,1)
#Print the queens in the board and their coordinates
print (Board)
Queenaux = (row,i)
Board.append(Queenaux)

由于这些行,Board 包含元组。您必须通过使 Queenaux 成为 Queen 实例来修复它,如下所示:

Queenaux = Queen(row,i)

另请注意,NQueens 没有 return 任何内容,因此您不应将其分配给 Board。只需调用函数并让它进行修改。