Home > Software engineering >  Removing global variable from recursive function
Removing global variable from recursive function

Time:03-07

rev = 0

def reverse(n):
    global rev
    if n > 0:
        r = n % 10 #final digit
        rev = rev * 10   r
        reverse(n // 10) 
        
    return rev

print(reverse(123))

This is a recursive function that reverses a number. I want to remove the global variable. When I do that, I get a different answer than expected. How can I define the rev variable inside the function, and still get the same answer?

CodePudding user response:

Yes, you can use a default parameter and then pass in the intermediate values through that parameter:

def reverse(n, rev=0):
    if n > 0:
        r = n % 10
        rev = reverse(n // 10, rev * 10   r) 
        
    return rev

print(reverse(123)) # Prints 321

CodePudding user response:

Let's start by writing a recursive reverse function that takes an accumulator argument.

def reverse(n, acc):
    if n <= 0:
        return acc
    else:
        return reverse(n // 10, acc * 10   (n % 10))

If we call reverse(123, 0) we get 321.

But aside from the method already shown with a default value for the accumulator parameter, we can "hide" that initial value by using an inner function.

def reverse(n):
    def reverse_helper(n, acc):
        if n <= 0:
            return acc
        else:
            return reverse_helper(n // 10, acc * 10   (n % 10))
    return reverse_helper(n, 0)
  • Related