Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - using a shared variable in a recursive function

I'm using a recursive function to sort a list in Python, and I want to keep track of the number of sorts/merges as the function continues. However, when I declare/initialize the variable inside the function, it becomes a local variable inside each successive call of the function. If I declare the variable outside the function, the function thinks it doesn't exist (i.e. has no access to it). How can I share this value across different calls of the function?

I tried to use the "global" variable tag inside and outside the function like this:

global invcount  ## I tried here, with and without the global tag

def inv_sort (listIn):
    global invcount   ## and here, with and without the global tag

    if (invcount == undefined):  ## can't figure this part out
        invcount = 0

    #do stuff

But I cannot figure out how to check for the undefined status of the global variable and give it a value on the first recursion call (because on all successive recursions it should have a value and be defined).

My first thought was to return the variable out of each call of the function, but I can't figure out how to pass two objects out of the function, and I already have to pass the list out for the recursion sort to work. My second attempt to resolve this issue involved me adding the variable invcount to the list I'm passing as the last element with an identifier, like "i27". Then I could just check for the presence of the identifier (the letter i in this example) in the last element and if present pop() it off at the beginning of the function call and re-add it during the recursion. In practice this is becoming really convoluted and while it may work eventually, I'm wondering if there is a more practical or easier solution.

Is there a way to share a variable without directly passing/returning it?

like image 596
Alium Britt Avatar asked May 20 '14 14:05

Alium Britt


People also ask

Can recursion have 2 base cases?

A recursive implementation may have more than one base case, or more than one recursive step. For example, the Fibonacci function has two base cases, n=0 and n=1.

What does recurse mean in Python?

Recursive Functions in Python A recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will continue to call itself and repeat its behavior until some condition is met to return a result.

Can you use loops in recursive functions?

All iterative loops can be made into recursive functions. However, not ALL recursive functions can be iterative loops, or they are at least VERY complex. You won't find recursion in simple applications. However, they can be particularly useful in mathematical programming, searching algorithms and compilers.

What is indirect recursion in Python?

Functions that call itself or two functions that call each other mutually. The functions that call itself are direct recursive and when two functions call each other mutually, then those functions are called indirect recursive functions.


2 Answers

There's couple of things you can do. Taking your example you should modify it like this:

invcount = 0

def inv_sort (listIn):
    global invcount

    invcount += 1

    # do stuff

But this approach means that you should zero invcount before each call to inv_sort. So actually its better to return invcount as a part of result. For example using tuples like this:

def inv_sort(listIn):

    #somewhere in your code recursive call
    recursive_result, recursive_invcount = inv_sort(argument)

    # this_call_invcount includes recursive_invcount
    return this_call_result, this_call_invcount   
like image 55
Alex Shkop Avatar answered Sep 18 '22 16:09

Alex Shkop


An alternative might be using a default argument, e.g.:

def inv_sort(listIn, invcount=0):
    ...
    invcount += 1
    ...
    listIn, invcount = inv_sort(listIn, invcount)        
    ...
    return listIn, invcount

The downside of this is that your calls get slightly less neat:

l, _ = inv_sort(l) # i.e. ignore the second returned parameter

But this does mean that invcount automatically gets reset each time the function is called with a single argument (and also provides the opportunity to inject a value of invcount if necessary for testing: assert result, 6 == inv_sort(test, 5)).

like image 34
jonrsharpe Avatar answered Sep 19 '22 16:09

jonrsharpe