0
Can anyone tell me how the following code operates , I don't know why "return fib(n-1) + fib(n-2) " is given
def fib(n): if n==0: return 0: if n==1: return 1: return fib(n-1) + fib(n-2) x=1 x+=1 print(fib(x))
1 Antwort
+ 2
Hi!
That is because you use recursion. That also means you use the function you define to solve the problem.
In Fibonacci's case you know that a fibonacci number ist the sum of two numbers before that number.
Fibonacci numbers = 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on.
We apply the function fib on that:
fib(2) = fib(2 - 1) + fib(2 -2) = fib(1) + fib(0) = 1 + 0 = 1 (True)
fib(3) = fib(3 - 1) + fib(3 - 2) = fib(2) + fib(1) = 1 + 1 = 2 (True)
fib(4) = fib(4 - 1) + fib(4 - 2) = fib(3) + fib(2) = 1 + 2 = 3 (True)
.............
.............
For every fib-number you need the two precedent numbers!
That why we have defined the beginning condition for 0 and 1.
You have to remove ":" after every "return"
You do not need x = 1 and x += 1 and print(fib(x)) after "return fib(n-1) + fib(n-2)"!
Here an adjustment:
def fib(n):
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)
If you want to use the function somewhere for a certain number m, simply call it with fib(m)!
I hope it helps!
The indentation is very important!