gpt4 book ai didi

python - 将多个返回语句拆分为不同的函数

转载 作者:行者123 更新时间:2023-11-28 17:37:02 25 4
gpt4 key购买 nike

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

  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

这会导致最大递归深度。我对如何解决这个问题有点迷茫,我以前从来没有真正尝试过拆分多个 return 语句。任何指示或提示都会有所帮助。

最佳答案

如果您想做的只是删除多个返回值,这就可以了

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

现在,我觉得还算干净

关于python - 将多个返回语句拆分为不同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com