Python递归函数返回Nonetyp

2024-10-01 09:22:08 发布

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

我有一个函数,递归地搜索2d矩阵,找到一个值0并返回它的位置。代码如下:

    def findNextZero(x, y, board):
       if board[x][y] == 0:
          return (x, y)
       else:
           if y == (SIZE-1):
              # if its at the edge of the "board", the 2d matrix
              findNextZero(x+1, 0, board)
           else:
              findNextZero(x, y+1, board)

当我打印(x,y)时,函数将打印正确的元组。但是,如果我尝试返回它,它将返回值为None。为什么会这样?在


Tags: ofthe函数代码boardsizereturnif
1条回答
网友
1楼 · 发布于 2024-10-01 09:22:08

您忽略了递归调用的返回值。为以下对象添加return语句:

def findNextZero(x, y, board):
    if board[x][y] == 0:
        return (x, y)
    else:
        if y == (SIZE-1):
            # if its at the edge of the "board", the 2d matrix
            return findNextZero(x+1, 0, board)
        else:
            return findNextZero(x, y+1, board)

如果没有这些return,那么findNextZero()函数只会结束而不显式返回任何内容,结果无论如何都会返回默认的返回值。在

相关问题 更多 >