gpt4 book ai didi

python - 如何避免在此递归函数中使用全局变量并改进我的代码?

转载 作者:太空宇宙 更新时间:2023-11-03 20:42:07 26 4
gpt4 key购买 nike

我制作了下一个函数来解决老鼠迷宫的问题,老鼠只能向前和向下移动,我需要找到可能的路径数量。我做到了,但我想避免全局变量“possible_ways”。有哪些方法可以改进我的代码?

possible_ways = 0

def solve(n,x,y):
if x == n-1 and y == n-1:
global possible_ways
possible_ways = possible_ways+1
return True
if x<=n-1 and y<=n-1:
solve(n,x+1,y)
solve(n,x,y+1)

solve(4,0,0)

print(possible_ways)

最佳答案

在这种情况下,您可以使函数返回一个值(对于其中所有可能的代码路径 - 当第一个 if 条件不成立时,您的代码返回 None):

def solve(n,x,y):
if x == n-1 and y == n-1:
return 1

if x <= n-1 and y <= n-1:
return solve(n,x+1,y) + solve(n,x,y+1)

return 0

possible_ways = solve(4,0,0)
print(possible_ways)

关于python - 如何避免在此递归函数中使用全局变量并改进我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56799234/

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