在Python程序中计数递归!

18 投票
5 回答
81776 浏览
提问于 2025-04-16 14:27

我需要统计一个Python程序中递归调用的次数。简单来说,我需要一个类似于C语言中的静态变量的东西,用来记录这个函数被调用了多少次。

5 个回答

9

你可以定义一个可调用的计数器类,这样你就可以把任何函数包装起来:

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

这样做的好处是,你可以对任何函数使用这个计数器,而不需要修改函数的参数。

编辑:感谢 @Tom Zych 发现了一个错误。为了让这个功能正常工作,recur 这个名字需要被可调用类的实例隐藏起来。关于装饰器的更多信息可以在这里找到:

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

20

另一种方法是使用 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
>>> 
45

只需在递归中传递一个计数器

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

或者我相信有一些很酷的装饰器,我现在要去研究一下...

撰写回答