我得到了这个代码,基本上如果我输入:01,那么1将被分配到这个相邻矩阵的位置01,我称之为棋盘。问题是一个大小为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
时启动处理,而不是在启动后启动处理因为
chessboard
首先是一个整数列表(为什么?),在循环中被一个整数列表替换,而循环只执行第一次迭代,所以出现了这个错误你需要从
print(chessboard)
中删除所有内容但是,在没有这样的循环的情况下初始化
chessboard
更好(在外循环中使用列表理解而不是乘法,以生成每行的单独引用):相关问题 更多 >
编程相关推荐