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
精彩评论