+ 1
can any one explain this to me ?
What is the result of this code? def fib(x): if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2) print(fib(4))
5 Answers
+ 7
This is recursive though. So you have to keep doing it until you get to 1 or 0.
fib(2) will return fib(1) + fib(0).
Each of those will return 1 each, so fib(2) = 1+1 = 2
fib(3) returns fib(2) and fib(1)
We already know that fib(2) = 2
So fib(3) is 2 + 1= 3
Therefore: fib(3) + fib(2) = (1 + 1 + 1 ) + (1 + 1) = 5.
+ 6
OUTPUT: 5
Just replace 'x' with the number that's being fed to it in order to understand. In this case, 'x' will equal 4. 'x' isn't equal to 0 or 1, so we'll use the else statement.
return fib(4-1) + fib(4-2)
v
return fib(3) + fib(2)
^Neither of those are 0 or 1. 3 + 2 = 5.
+ 1
@Jakob Marley, how can you say that:
return fib(3) + fib(2) = 3+2 = 5
Adding two functions as if they are numbers! xD
Anyways, @Mike Shaw had explained it correctly ^_^
+ 1
Fib(4)
If x is not 0 or 1 so else
Fib(4-1) + pending_1
Fib(3)
If x is not 0 or 1 so else
Fib(3-1) + pending_2
Fib(2)
If x is not 0 or 1 so else
Fib(2-1) + pending_3
Fib(1)
If return 1 1st Ans 1
*Pending_1
Fib(4-2)
Fib(2)
If x is not 0 or 1 so else
Fib(2-1) + pending_4
Fib(1)
If return 1 2nd Ans 1
*Pending_2
Fib(3-2)
Fib(1)
If return 1 3rd Ans 1
*Pending_3
Fib(2-2)
Fib(0)
If return 1 4th Ans 1
*Pending_4
Fib(2-2)
Fib(0)
If return 1 5th Ans 1
All ans 1+1+1+1+1=5
0
5 is the answer