user3716774 user3716774 - 1 year ago 138
Python Question

how to count function calling time within that function and the number can be restored in Python?

For example I have a function like this:

def a (x):
if f(x) < 0:
a(x) # If a(x) is called over 30 times, then stop calling a(x) and return certain value.
else: return f(x)

I want to count the number of function calling under the if statement. Once the calling number is over certain number, then I can stop running a(x) and return certain values, and the calling number can be restored.

How can I do this? The regular counting wrapper is for the whole function, which is not suitable in this case I guess?

------------ Update -------------

Thanks to @Yevhen Kuzmovych now I have an example function like this:

def a (x, depth = 0):
b = x - 1
print(depth, b)
if b < 0:
if depth < 10:
a(b, depth + 1)
return b
return b

c = a(0) # this doesn't have a value

so with this function, c doesn't have a value. I don't understand. It seems the value is not returned.

Answer Source

You need to count depth of recursion:

def a(x, depth = 0):
    if f(x) < 0:
        if depth < certain_number:
            return a(x, depth + 1)
            return certain_value
        return f(x)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download