user3716774
user3716774

Reputation: 441

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):
    f(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)
        else:
            return b
    else:
        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.

Upvotes: 0

Views: 74

Answers (2)

Artyer
Artyer

Reputation: 40811

Recursion (Calling a function within a function) is useful sometimes, but in this case it is easy to avoid it and will probably be faster to do so. In Python, you can only go around 970 function calls before a RuntimeError: maximum recursion depth exceeded while ....

An iterative way to do this would be to just use a range in a for loop, where the times variable is the "calling number" (Or how many times the function has been called).

def a(x, retry=0):
    for times in range(1, retry + 1):  # xrange in Python 2
        processed = f(x)  # Store the value so you don't need to call f(x) again
        if processed < 0:
            continue  # Try again, having gone through one more item in the range
        return processed
    return certain_value  # You only get here if the range runs out

Upvotes: 0

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12140

You need to count depth of recursion:

def a(x, depth = 0):
    f(x)
    if f(x) < 0:
        if depth < certain_number:
            return a(x, depth + 1)
        else:
            return certain_value
    else:
        return f(x)

Upvotes: 1

Related Questions