Counting recursive function calls

I have a recursive code for catalytic numbers. I managed to write a recursive call, but for some reason the counter is not working correctly. for example, the number of calls for the 7th Catalan number should be 1215. the return value should be a tuple of the Catalan number and the number of calls, for example: (429,1215). source:

def catalan_rec(n):
    if n<=1:
        return 1
    res=0
    for i in range(n):
        res+=catalan_rec(i)*catalan_rec(n-i-1)
    return res

counter code:

def catalan_rec_count(n,counter=1):
    if n<=1:
        return 1
    res=0
    for i in range(n):
        res+=catalan_rec_count(i,counter+1)*catalan_rec_count(n-i-1,counter+1)        
    return (res,counter)

early!

+4
source share
2 answers

python allows you to attach a variable ( catalan.counterin the snippet below) to the function object, so you do not need to go through the counter all the time and do not need a global variable:

def catalan(n):

    catalan.counter += 1

    if n <= 1:
        return 1
    res = 0
    for i in range(n):
        res += catalan(i) * catalan(n-i-1)
    return res

catalan.counter = 0

print(catalan(5))
print(catalan.counter)

, : lru_cache; , , , ; , n.

from functools import lru_cache

@lru_cache(maxsize=128)
def catalan(n):

    ...

... , closure , :

def make_catalan():

    counter = 0

    def catalan(n):

        nonlocal counter
        counter += 1
        catalan.counter = counter

        if n <= 1:
            return 1
        res = 0
        for i in range(n):
            res += catalan(i) * catalan(n-i-1)
        return res

    return catalan

catalan_1 = make_catalan()
print(catalan_1(2))
print(catalan_1.counter)

catalan_2 = make_catalan()
print(catalan_2(3))
print(catalan_2.counter)
+7

res+=catalan_rec_count(i,counter+1)*catalan_rec_count(n-i-1,counter+1), , , counter+1 , , .

def catalan_rec_count(n,counter=1):
    if n<=1:
        return (1, counter) #remember to return the counter in this case too!
    res=0
    for i in range(n):
        #get the recursive results and counters for both calls
        #don't pass counter+1 to it, it should count how many times it is called on it own
        partial1, inner_c1 = catalan_rec_count(i)
        partial2, inner_c2 = catalan_rec_count(n-i-1)
        #apply the logic with the actual result and add to the counter
        res+=partial1*partial2
        counter+= inner_c1 + inner_c2
    return (res,counter)
+5

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


All Articles