函数f定义如下:
def f(a, b):
if a <= 0 or b <= 0:
return a + b
else:
s = 0
if b * b % (a + b) != 0:
s += f(a, b - 3)
if a * a % (a + b) != 0:
s += f(a - 2, b)
if a == b - 1:
s += f(a - 3, b - 2)
return s
问题是:“给定f(4,9),函数”f“执行多少次?”例如,对于f(0,0),函数“f”将被执行一次,因为第一次也被考虑在内。有人可以向我解释,我怎么能找到执行的数量? (例子将是理想的。)比你提前!
答案 0 :(得分:1)
您可以将属性附加到该功能:
def f(a, b):
f.num += 1
if a <= 0 or b <= 0:
...
结果:
>>> f.num = 0
>>> f(0, 0)
0
>>> print(f.num)
1
>>> f.num = 0
>>> f(3, 5)
4
>>> print(f.num)
13
答案 1 :(得分:0)
您可以递增一个全局计数器,一个包含在列表中的int,在函数中递增它并在调用后打印结果:
i = [0]
def f(a, b):
i[0] += 1
if a <= 0 or b <= 0:
return a + b
else:
s = 0
if b * b % (a + b) != 0:
s += f(a, b - 3)
if a * a % (a + b) != 0:
s += f(a - 2, b)
if a == b - 1:
s += f(a - 3, b - 2)
return s
f(2, 34)
print(i[0])
答案 2 :(得分:-1)
我不相信全局变量,因为高可用范围,即每个人都可以访问全局变量。相反,您可以保留一个递归变量,该变量计算函数被调用的次数。
def f(a, b, count=0):
count+=1
if a <= 0 or b <= 0:
return [a + b, count]
else:
s = 0
if b * b % (a + b) != 0:
l = f(a, b - 3,count)
s += l[0]
count+=l[1]
if a * a % (a + b) != 0:
l = f(a - 2, b, count)
s += l[0]
count+=l[1]
if a == b - 1:
l = f(a - 3, b - 2, count)
s += l[0]
count+=l[1]
return [s,count]