Python - using a shared variable in a recursive function

I am 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 a variable inside a function, it becomes a local variable inside each subsequent function call. If I declare a variable outside the function, the function considers that it does not exist (i.e. Does not have access to it). How can I share this value with different function calls?

I tried using the "global" variable tag inside and outside the function as follows:

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 the undefined status of a global variable and assign it a value for the first recursion call (because in all consecutive recursions it must have a value and be defined).

, , , , . invcount , , "i27". ( i ) () . , , , , .

/?

+4
4

, . , :

invcount = 0

def inv_sort (listIn):
    global invcount

    invcount += 1

    # do stuff

, inv_sort invcount. invcount . , , :

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   
+6

, :

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

, :

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

, invcount reset , ( invcount, : assert result, 6 == inv_sort(test, 5)).

+5

In Python, there is no such thing as the "undefined" variable, and you do not need it.

Outside the function, set the variable to 0. Inside the loop, use the keyword global, and then increment.

invcount = 0
def inv_sort (listIn):
    global invcount

    ... do stuff ...

    invcount += 1
+2
source

Assuming you don't need to know the counter inside the function, I would approach this using the decorator function:

import functools

def count_calls(f):
    @functools.wraps(f)
    def func(*args):
        func.count += 1
        return f(*args)
    func.count = 0
    return func

Now you can decorate your recursive function:

@count_calls
def inv_sort(...):
    ...

And check or reset countbefore or after calling it:

inv_sort.count = 0
l = inv_sort(l)
print(inv_sort.count)
+1
source

Source: https://habr.com/ru/post/1541283/


All Articles