【问题标题】:Python recursive function returning NonetypePython递归函数返回Nonetype
【发布时间】:2013-11-05 19:29:50
【问题描述】:

我有一个函数可以递归地搜索二维矩阵以找到值 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。为什么会出现这种情况?

【问题讨论】:

    标签: python recursion


    【解决方案1】:

    忽略递归调用的返回值。为这些添加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)
    

    如果没有这些returns,findNextZero() 函数将直接结束而不会显式返回任何内容,从而导致无论如何都返回默认返回值。

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 1970-01-01
      • 2015-11-09
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 2020-08-24
      相关资源
      最近更新 更多