Yolanda Hui
Yolanda Hui

Reputation: 55

Recursive code not displaying the right output?

I have the following illustrative recursive code to calculate fibonacci numbers, but it is not give me the right output.

def fib(n):
    print("calculate f", n)

    if n == 0 or n == 1:
        print("return", n)
        return n

    print("f", n, "=", "f", (n-1), "+", "f", (n-2))

    return fib(n-1) + fib(n-2)

n = int(input("calculate f "))
fib(n)

print("f", n, "=", n)
print("return", n) 

When I input 2, it gives me this output:

calculate f 2

f 2 = f 1 + f 0

calculate f 1

return 1

calculate f 0

return 0

f 2 = 2

return 2

The last 2 lines of output are line though, it should be f 2 = 1 and return 1, how do I correct my code?

Upvotes: 3

Views: 76

Answers (2)

user10325516
user10325516

Reputation:

So basically you want to inflate the code with print()s to get the output like in the images you have provided. Now you missing f 2 = 1 (you and images also missing f 0 = 0 and f 1 = 1 - not a problem I guess). The issue is solvable pretty easily since this information is available in the function fib(), so print it in the right place. To achieve this you need to modify the code of the function fib() a little bit - (1) single return instead of multiple, (2) keep all the print()s inside the function:

def fib(n):
    print("calculate f", n)

    if n == 0 or n == 1:
        ans = n
    else:
        print("f", n, "=", "f", (n-1), "+", "f", (n-2))
        ans = fib(n-1) + fib(n-2)
        print("f", n, "=", ans)

    print('return', ans)
    return ans

fib(3)

Output:

calculate f 3
f 3 = f 2 + f 1
calculate f 2
f 2 = f 1 + f 0
calculate f 1
return 1
calculate f 0
return 0
f 2 = 1
return 1
calculate f 1
return 1
f 3 = 2
return 2

Now the output looks just like the one in the images if my eyes don't lie to me.

Upvotes: 1

Jon Deaton
Jon Deaton

Reputation: 4379

It is because you have

print("f", n, "=", n)

instead of

print("f", n, "=", fib(n))

If you also want to correct the final line of code you'll want to store the return value of the fibonacci function in an intermediate value and then print it like this

result = fib(n)
print("f", n, "=", result)
print("return", result)

Upvotes: 3

Related Questions