开发者

Counting recursion in a python program! [duplicate]

开发者 https://www.devze.com 2023-02-19 17:15 出处:网络
This question already has answers here: How to keep count in a recursive function? (13 answers) 开发者_StackOverflowClosed 5 years ago.
This question already has answers here: How to keep count in a recursive function? (13 answers) 开发者_StackOverflowClosed 5 years ago.

I need to count the number of times recursion in a python program. So basically I need a static variable kind of thing (like in C) which can count the number of times the function is called.


Just pass a counter with the recursion

def recur(n, count=0):
    if n == 0:
        return "Finished count %s" % count
    return recur(n-1, count+1)

Or im sure there is some fancy decorator, Im gonna investigate that now...


Another method using global:

>>> def recur(n):
...     global counter
...     counter+=1
...     if n==0:
...         return -1
...     else:
...         return recur(n-1)
... 
>>> counter = 0
>>> recur(100)
-1
>>> print counter
101
>>> 


You can define a Counter callable class with which you can wrap any function:

class Counter(object) :
    def __init__(self, fun) :
        self._fun = fun
        self.counter=0
    def __call__(self,*args, **kwargs) :
        self.counter += 1
        return self._fun(*args, **kwargs)

def recur(n) :
    print 'recur',n
    if n>0 :
        return recur(n-1)
    return 0

recur = Counter(recur)

recur(5)

print '# of times recur has been called =', recur.counter

The advantage here being that you can use it for any function, without having to modify it's signature.

EDIT: Thanks to @Tom Zych for spotting a bug. The recur name has to be masked by the callable class instance for this to work. More info on decorators here:

http://wiki.python.org/moin/PythonDecoratorLibrary#Counting_function_calls


One way would be to use a list containing one element that keeps a count of how many times the function was entered.

>>> counter=[0]
>>> def recur(n):
...     counter[0]+=1
...     if n==0:
...             return -1
...     else:
...             return recur(n-1)
... 
>>> recur(100)
-1
>>> print counter[0]
101


>>> def func(n, count=0):
...     if n==0:
...             return count
...     else:
...             return func(n-1, count+1)
... 
>>> func(100)
100
0

精彩评论

暂无评论...
验证码 换一张
取 消