[英]Why doesn't my code work for N queens?
我得到了這段代碼,基本上如果我輸入:0 1,那么將在這個稱為棋盤的鄰接矩陣上將0 1分配給位置0 1。問題是尺寸為4x4的棋盤,如果我輸入
1 0,
3 1,
0 2,
2 3
它應該輸出
[[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]]
但我收到“ int”對象錯誤,此行不支持項目分配:
chessboard[pos[0]][pos[1]] = 1
這是我的代碼。
N = int ( input (" Enter N: ") ) # Makes an empty chessboard of size N by N
chessboard = N*[0]
for row in range (N) :
chessboard[row]=N*[0]
print(chessboard)
# This while loop asks the user for input N times and checks that it ’s validity and places the queens
inputCount = 0
while inputCount < N:
pos = input (" Please input the Queen position ")
pos = pos.split () # Cast the input as integers
pos [0] = int (pos [0])
pos [1] = int (pos [1])
# If the input is out of range , inform the user , decrement the counter set the input to 0 1
if pos [0] < 0 or pos [0] >N-1 or pos [1] < 0 or pos [1] >N-1:
print (" Invalid position ")
pos [0] = pos [1] = 0
inputCount=inputCount-1
else :# Uses the input to place the queens
chessboard[pos[0]][pos[1]] = 1
inputCount += 1
print ( chessboard )
chessboard = N*[0]
for row in range (N) :
chessboard[row]=N*[0]
print(chessboard)
# here you're still in the chessboard init loop
inputCount = 0
while inputCount < N:
您正在初始化chessboard
開始處理, 而不是在開始之后。
由於國際chessboard
首先是一個整數列表(為什么?),由循環中的整數列表取代,而您的循環僅執行第一次迭代,因此會出現此錯誤。
您需要取消縮進print(chessboard)
但最好不要這樣循環就初始化chessboard
(在外循環中使用列表推導而不是乘法來生成每一行的單獨引用):
chessboard = [[0]*N for _ in range(N)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.