我无法打印一个变量的最终值变量

由网友(杀死喜欢)分享简介:我是新的Python和我想的写 recAdd 在我递归斐波纳契版本的最终值。这是我的code:I'm new in Python and I'm trying the write to final value of recAdd on my fibonacci recursive version. Here is...

我是新的Python和我想的写 recAdd 在我递归斐波纳契版本的最终值。这是我的code:

I'm new in Python and I'm trying the write to final value of recAdd on my fibonacci recursive version. Here is my code:

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 值?

After I called my function, it returns only fibonacci value and not recAdd.I want to print both of them. What should I do to print the recAdd value?

推荐答案

您需要迪登的打印,并将其放置在调用函数之后

You need to dedent the print and place it after you call the function

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)

您可以在一个包装封装本

You could encapsulate this in a wrapper

def fib_aux(n):
    global recAdd
    recAdd = 0
    fibonacciRecursive(5)
    print(recAdd)

然后,只需拨打

Then just call

fib_aux(5)

埋葬在功能逻辑是尴尬。这里有一种方法

Burying the logic in the function is awkward. Here is one way

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
阅读全文

相关推荐

最新文章