列表索引超出范围

时间:2014-03-29 20:13:03

标签: python error-handling indexing

我正在尝试为连接4编写程序,这是检查获胜者的功能。当我运行该函数时,我收到错误消息:list index超出范围。我该如何解决?

def winner(board):
    # Check rows for winner
    for c in range(NUM_ROWS): #number of rows
        for r in range(NUM_COLS-3): #number of columns filled to win
            if (board[r][c] == board[r][c + 1] == board[r][c + 2] == board[r][c + 3]) and (board[r][c] != " "):
                return true

    # Check columns for winner
    for c in range(NUM_COLS): #number of rows
        for r in range(NUM_ROWS-3): #number of columns filled to win 
            if (board[r][c] == board[r + 1][c] == board[r + 2][c] ==board[r + 3][c]) and (board[r][c] != " "):
                return true

    # Check diagonal (top-left to bottom-right) for winner
    for c in range(NUM_COLS-3): #number of columns in a winning diagonal 
        for r in range(NUM_ROWS): #number of rows in a winning diagonal
            if (board[r][c] == board[r + 1][c + 1] == board[r + 2][c + 2] == board[r + 3][c + 3]) and (board[r][c] != " "):
                return true


    # Check diagonal (bottom-left to top-right) for winner
    for r in range(NUMC_COLS-3): #columns to make a diagonal
        for c in range(NUM_ROWS-3): #rows to make a diagonal
            if (board[r][c] == board[r - 1][c + 1] == board[r - 2][c + 2] == board[r - 3][c + 3]) and (board[r][c] != " "):
                return true

    # No winner: return the empty string
    return False 

2 个答案:

答案 0 :(得分:2)

您的行和列循环交换:

for c in range(NUM_ROWS): #number of rows
    for r in range(NUM_COLS-3): #number of columns filled to win
        if (board[r][c] == board[r][c + 1] == board[r][c + 2] == board[r][c + 3]) and (board[r][c] != " "):

请注意,c)的范围超过NUM_ROWSr)的范围超过{{1 }}

您在最后一个嵌套循环中再次执行此操作:

NUM_COLS

但你也拼错了for r in range(NUMC_COLS-3): #columns to make a diagonal for c in range(NUM_ROWS-3): #rows to make a diagonal if (board[r][c] == board[r - 1][c + 1] == board[r - 2][c + 2] == board[r - 3][c + 3]) and (board[r][c] != " "): 所以你的程序从来没有这么远。

在第3个区块中,您还将超出NUMC_COLS值的范围:

r

当您到达# Check diagonal (top-left to bottom-right) for winner for c in range(NUM_COLS-3): #number of columns in a winning diagonal for r in range(NUM_ROWS): #number of rows in a winning diagonal if (board[r][c] == board[r + 1][c + 1] == board[r + 2][c + 2] == board[r + 3][c + 3]) and (board[r][c] != " "): return true 循环的最后一次迭代时,r + 1会引发IndexError,因为您没有将该循环限制为for r in range(NUM_ROWS)

答案 1 :(得分:1)

你需要解决这个问题:(看看你如何说r + 3 ......你可以说,对于NUM_ROWS + 3)

for c in range(NUM_COLS-3): #number of columns in a winning diagonal 
    for r in range(NUM_ROWS): #number of rows in a winning diagonal
        if (board[r][c] == board[r + 1][c + 1] == board[r + 2][c + 2] == board[r + 3][c + 3]) and (board[r][c] != " "):
            return true