列表索引超出范围(被绊倒的新手)

2024-04-16 06:26:17 发布

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

我是一个新手程序员,我试图从初学者过渡到中级水平,但有时我有问题排除和发现我的错误(s)。这是我正在解决的问题。我正在编写一个数独游戏,第一步是确保它是一个完美的正方形或矩阵。比如3x3或者9x9。在下面的代码中,您将看到我先获取行的计数,然后获取列的计数。如果这些数相等,那么它就是一个完美的正方形。你知道吗

def check_square(square):
    # Count Row
    i = 0
    j = 0
    countRow = 0
    countCol = 0

    while square[i][j] <= len(square):
        print("This is i:", i, "This is j:",j)
        countRow = countRow + 1
        j = j + 1
        if j == len(square):
            print(countRow)
            break

    i = 0
    j = 0
    while square[i][j] <= len(square):
        print("This is i:", i, "This is j:", j)
        countCol = countCol + 1
        i = i + 1
        if i == len(square):
            print(countCol)
            break

    if countRow == countCol:
        print("True")
        return True
    else:
        print("False")
        return False

当我经过这样一个完美的正方形时:

[[1, 2, 3, 4],
 [2, 4, 1, 3],
 [3, 1, 4, 2],
 [4, 3, 2, 1]]

我的代码传递并打印出“True”。但当我经过这样一个不完美的正方形时:

[[1, 2, 3],
[2, 4, 1],
[3, 1, 4],
[4, 3, 2]]

我的代码失败并给出错误:

Traceback (most recent call last):
  File "/Users/jim/PycharmProjects/Sudoku/sudoku.py", line 113, in <module>
    [4, 3, 2]])
  File "/Users/jim/PycharmProjects/Sudoku/sudoku.py", line 84, in check_square
    while square[i][j] < len(square):
IndexError: list index out of range

我浏览了我的代码,发现它在这行失败了:

while square[i][j] <= len(square):

例如,如果我有一个长度为4的正方形,当j=2且j增加1时,行中只有3个项目,它会抛出错误,因为它需要更多的项目。我真的被这些错误绊倒了,真的很沮丧,因为我还不知道如何修复它们。任何帮助都会很好。你知道吗

**编辑** 我的问题是不同的,因为我正在检查一个不完美的正方形。你知道吗


Tags: 代码truelenifischeck错误this
1条回答
网友
1楼 · 发布于 2024-04-16 06:26:17

如果square不是正方形,而是矩形,则需要处理两个长度:(a)行数,即len(square);和(b)列数,即len(square[0])。你知道吗

在第一个循环中,j遍历行,即示例中的0..3。但是它被用作列索引,即使有效的列索引只从0..2运行。因此,与其检查j == len(square),不如检查j == len(square[0])。你知道吗

相关问题 更多 >