我正在制作一个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)
答案 0 :(得分:0)
Queenaux = (row,i)
Board.append(Queenaux)
由于这些行,Board
包含元组。您必须通过Queenaux
Queen
实例来修复它,如下所示:
Queenaux = Queen(row,i)
另请注意,NQueens
并未返回任何内容,因此您不应将其分配给Board
。只需调用该函数并让它进行修改。