为什么我的代码对 N 皇后不起作用?
Why doesn't my code work for N queens?
我得到了这个代码,基本上如果我输入:0 1 那么 1 将被分配到这个邻接矩阵上的位置 0 1 我命名为 chessboard.Problem 是一个大小为 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' object does not support item assignment in this line:
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)]
我得到了这个代码,基本上如果我输入:0 1 那么 1 将被分配到这个邻接矩阵上的位置 0 1 我命名为 chessboard.Problem 是一个大小为 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' object does not support item assignment in this line:
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)]