Search code examples
pythonrecursionglobal-variablesrefactoring

How to avoid using a global variable in this recursion function and improve my code?


I made the next function to solve the problem of rat maze, where the rat only can move to forward and down, and i needed to find the number of ways possibles. I did it but i want to avoid the global variable "possible_ways". What are the way to improve my code ?

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)

Solution

  • In this case you can make the function return a value (for all possible code paths in it — your code returned None whenever the first if condition was untrue):

    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)