2017-10-14 4 views
0

Iが入力場合、私は基本的にこのコードを持って、1:0、次いで1 chessboard.Problemがサイズ4×4のchesboardするためのものであるように、私はNのクイーンに対してコードが機能しないのはなぜですか?

1 0, 
3 1, 
0 2, 
2 3 
を入力した場合、私は、名前この隣接行列上の位置0~1に割り当てられます

それが出力

[[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) 

答えて

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)] 
関連する問題