将多个return语句拆分为不同的函数

时间:2015-04-03 16:04:37

标签: python recursion

我正在实施一个回溯解决方案,并有多个return语句。我没有看到将其拆分为多个函数的方法,因此每个函数只有一个return语句。代码是..

  def solve_grid(self, grid, row=0, col=0):


    row, col = self.find_next(grid, row, col)
    if row == -1:
        return True
    for num in range(1,10):
        if self.isValid(grid, row, col, num):
            grid[row][col] = num
            if self.solve_grid(grid, row, col):
                return True
            grid[row][col] = 0
    return False

我已尝试将其拆分如下

def check(self, grid, row, col):
    boolean = None
    row, col = self.find_next(grid, row, col)
    if row == -1:
        boolean = True
    return boolean

def solve_grid(self, grid, row=0, col=0):

    boolean = None
    if not self.check(grid, row, col):
        for num in range(1,10):
            if self.isValid(grid, row, col, num):
                grid[row][col] = num
                if self.solve_grid(grid, row, col):
                    boolean = True
                else: 
                    boolean = False
            grid[row][col] = 0
    return boolean

这导致最大递归深度。我有点失去了如何解决这个问题,我从来没有真正尝试过多次返回语句。任何指针或提示都会有所帮助。

1 个答案:

答案 0 :(得分:1)

如果您要做的就是删除多个返回,这将执行此操作

def solve_grid(self, grid, row=0, col=0):
    row, col = self.find_next(grid, row, col)
    if row == -1:
        result = True
    else:
        result = False
        for num in range(1,10):
            if self.isValid(grid, row, col, num):
                grid[row][col] = num

                if self.solve_grid(grid, row, col):
                    result=True
                    break

                grid[row][col] = 0

    return result

您还可以将for循环转换为while以删除break

def solve_grid(self, grid, row=0, col=0):
    row, col = self.find_next(grid, row, col)
    if row == -1:
        result = True
    else:
        result = False
        num = 0
        while num < 9 and not result:
            num += 1
            if self.isValid(grid, row, col, num):
                grid[row][col] = num

                if self.solve_grid(grid, row, col):
                    result=True
                else:
                    grid[row][col] = 0

    return result

但我个人觉得你的原始形式更具可读性。

通过检查result

初始化row,最后一次简化可以消除一定程度的缩进
def solve_grid(self, grid, row=0, col=0):
    row, col = self.find_next(grid, row, col)
    result = (row == -1)
    num = 0
    while num < 9 and not result:
        num += 1
        if self.isValid(grid, row, col, num):
            grid[row][col] = num

            if self.solve_grid(grid, row, col):
                result=True
            else:
                grid[row][col] = 0


    return result

现在,我认为它相当干净