我是Python的新手,我正在尝试在我的斐波纳契递归版本上写入recAdd
的最终值。这是我的代码:
recAdd=0
def fibonacciRecursive(n):
global recAdd
if n==1 or n==0:
return n
else:
recAdd=recAdd+1
return fibonacciRecursive(n-1)+fibonacciRecursive(n-2)
print(recAdd)
在我调用我的函数后,它只返回斐波那契值,而不是recAdd
。我想打印它们。我该怎么做才能打印recAdd
值?
答案 0 :(得分:1)
您需要致谢print
并在调用函数
def fibonacciRecursive(n):
global recAdd
if n == 1 or n == 0:
return n # <-- should this be return 1?
else:
recAdd = recAdd + 1
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2)
recAdd = 0
fibonacciRecursive(5)
print(recAdd)
您可以将其封装在包装器中
def fib_aux(n):
global recAdd
recAdd = 0
fibonacciRecursive(5)
print(recAdd)
然后致电
fib_aux(5)
埋没函数中的逻辑很尴尬。这是一种方式
def fibonacciRecursive(n, print_recAdd=True):
global recAdd
if n == 1 or n == 0:
retval = n # <-- should this be 1?
else:
recAdd = recAdd + 1
retval = fibonacciRecursive(n - 1, False) + fibonacciRecursive(n - 2, False)
if print_recAdd:
print recAdd
return retval