I got this code and basically if I input: 0 1 then 1 will be assigned to position 0 1 on this adjacency matrix I named as chessboard.Problem is for a chesboard of size 4x4,if I entered
1 0,
3 1,
0 2,
2 3
it is supposed to output
[[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]]
but I get an error of 'int' object does not support item assignment in this line:
chessboard[pos[0]][pos[1]] = 1
This is my code.
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:
you're starting your processing while initializing chessboard
, not after it has started.
Since chessboard
is first a list of integers (why that?), replaced by a list of list of integers in your loop, and your loop is only executing the first iteration, you're getting this error.
you need to unindent everything from print(chessboard)
But it's even better to just initialize chessboard
without a loop like this (using list comprehension in the outer loop instead of multiplication, to generate a separate reference of each row):
chessboard = [[0]*N for _ in range(N)]