3 回答

TA貢獻1859條經驗 獲得超6個贊
使用裝飾器
使用函數屬性
法典
def call_counter(func):
" Does the call count for any function "
def helper(x):
helper.calls += 1
return func(x)
helper.calls = 0
return helper
@call_counter
def fib(n):
if n ==0 or n == 1:
return 1
return fib(n - 1) + fib(n - 2)
用法
fib(5)
print(fib.calls)
fib(10)
print(fib.calls) # Keeps running total so will be from previous
# fib(5) plus current fib(10)
# To reset counter
fib.calls = 0
使用類
參考
法典
class countCalls(object):
"""Decorator that keeps track of the number of times a function is called.
::
>>> @countCalls
... def foo():
... return "spam"
...
>>> for _ in range(10)
... foo()
...
>>> foo.count()
10
>>> countCalls.counts()
{'foo': 10}
Found in the Pythod Decorator Library from http://wiki.python.org/moin web site.
"""
instances = {}
def __init__(self, func):
self.func = func
self.numcalls = 0
countCalls.instances[func] = self
def __call__(self, *args, **kwargs):
self.numcalls += 1
return self.func(*args, **kwargs)
def count(self):
"Return the number of times this function was called."
return countCalls.instances[self.func].numcalls
@staticmethod
def counts():
"Return a dict of {function: # of calls} for all registered functions."
return dict([(func.__name__, countCalls.instances[func].numcalls) for func in countCalls.instances])
@countCalls
def fib(n):
if n ==0 or n == 1:
return 1
return fib(n - 1) + fib(n - 2)
例
print(fib(3)) # Output 3
print(fib.count()) # Output 5
優勢
允許獲取所有已注冊函數的計數(即使用裝飾器注冊)
@countCalls
def f(n):
pass # dummy function
@countCalls
def g(n):
pass # dummy function
for i in range(5):
f(i)
for i in range(10):
g(i)
print(countCalls.counts())
# Outputs: {'f': 5, 'g': 10}

TA貢獻1784條經驗 獲得超9個贊
def fib(n):
if n <= 1:
return n, 1
fib_one = fib(n - 1)
fib_two = fib(n - 2)
#Return the result and the number of function calls (+ 1 for the current call)
return fib_one[0] + fib_two[0], fib_one[1] + fib_two[1] + 1
if __name__ == '__main__':
number_of_function_calls = fib(4)[1]
Fib(4) 應該返回 9,它確實如此
fib(4)
fib(3) fib(2)
fib(2) fib(1) fib(1) fib(0)
fib(1) fib(0)

TA貢獻1921條經驗 獲得超9個贊
問題是“顯而易見的”,如果你費心去跟蹤你正在使用的值:
return fibonnaci(n - 1) + fibonnaci(n - 2), total_call
當是 3 時,它嘗試“添加”斐波那契(2),元組,和斐波那契(1),整數。這不是一項合法的行動。您需要正則化返回值。你不能神奇地只返回值(而不是計數),而這正是你想要的;你必須明確地編程差異:肢解元組并添加組件值。n
1
從您的基本案例開始
return 1, 0
遞歸情況需要添加組件。實施留給學生練習。
添加回答
舉報