0

我是 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价值?

4

1 回答 1

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
于 2013-10-08T22:49:36.697 回答