簡體   English   中英

將多個return語句拆分為不同的函數

[英]splitting multiple return statements into different functions

我正在實現一個回溯解決方案,並有多個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

這導致最大遞歸深度。 我有點失去了如何解決這個問題,我從來沒有真正嘗試過多次返回語句。 任何指針或提示都會有所幫助。

如果您要做的就是刪除多個返回,這將執行此操作

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

但我個人覺得你的原始形式更具可讀性。

最后的簡化通過檢查row初始化result消除一定程度的縮進

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

而現在,我認為它相當干凈

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM