我是Python新手,我正在尝试在fibonacci递归版本上写入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
值? 最佳答案
您需要删除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