2017-10-14 51 views
0

我得到這個代碼和基本上如果我輸入:0 1 1然後將被分配到在該鄰接矩陣我命名爲chessboard.Problem爲4×4大小的chesboard位置0 1,如果我進入爲什麼我的代碼不適用於N個皇后?

1 0, 
3 1, 
0 2, 
2 3 

它應該輸出

[[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]] 

,但我得到「詮釋」對象的錯誤不支持該訂單項任務:

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) 

回答

2
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)] 
相關問題