为什么我的代码不适用于N皇后区?

2024-06-16 19:16:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了这个代码,基本上如果我输入: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 )

Tags: oroftheposforinput棋盘range
1条回答
网友
1楼 · 发布于 2024-06-16 19:16:57
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)]

相关问题 更多 >