Counting recursion in a python program! [duplicate

2020-07-04 07:20发布

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.

5条回答
地球回转人心会变
2楼-- · 2020-07-04 07:23

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...

查看更多
神经病院院长
3楼-- · 2020-07-04 07:25
>>> def func(n, count=0):
...     if n==0:
...             return count
...     else:
...             return func(n-1, count+1)
... 
>>> func(100)
100
查看更多
对你真心纯属浪费
4楼-- · 2020-07-04 07:36

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
>>> 
查看更多
再贱就再见
5楼-- · 2020-07-04 07:36

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
查看更多
兄弟一词,经得起流年.
6楼-- · 2020-07-04 07:48

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

查看更多
登录 后发表回答