+ 1

Please explain this code

def fib(n): if n == 0: return 0 elif n == 1: return 1 elif n == 2: return 1 else: return fib(n-1) + fib(n-2) print (fib(10)) Why 55?

22nd Jun 2019, 5:31 PM
Zakhar
4 Respuestas
+ 8
It is a recursive code for calculating the numbers of Fibonacci sequence. fib(1)=1 fib(2)=1 fib(3)=fib(2)+fib(1)=1+1=2 fib(4)=fib(3)+fib(2)=2+1=3 fib(5)=fib(4)+fib(3)=3+2=5 fib(6)=fib(5)+fib(4)=5+3=8 fib(7)=fib(6)+fib(5)=8+5=13 fib(8)=fib(7)+fib(6)=13+8=21 fib(9)=fib(8)+fib(7)=21+13=34 fib(10)=fib(9)+fib(8)=34+21=55
22nd Jun 2019, 5:55 PM
Aleksei Kubarkov
Aleksei Kubarkov - avatar
+ 3
You probably know the fibonacci sequence: 1, 1, 2, 3, 5, 8... The formula to the nth number is: an = a(n - 1) + a(n - 2). It does the same: It returns the formula if it isn't 1 or 2, the other ones are predefined values. Let's say you want the 3rd element. You get fib(n - 1) and fib(n - 2), which are both one, and 1 + 1 is 2. If you want the 4th number, you get fib(2) and fib(3). fib(2) is 1, and fib(3) is calculated like above, so it's 2 + 1, which is 3. You can calculate it up to 10
22nd Jun 2019, 5:54 PM
Airree
Airree - avatar
+ 2
fib is a recursive function which can call itself. when you call 'fib(10)' the function will be called 2 more times once with the value 9 (10-1) and 8 (10-2), which will call themself until the number 0, 1 or 2 are reached. step by step: fib(10) fib(9) + fib(8) (fib(8) + fib(7)) + (fib(7) + fib(6)) (fib(7) + fib(6) + (fib(6) + fib(5)) + (fib(6) + fib(5)) + (fib(5) + fib(4)) (fib(6) + fib(5)) + (fib(5) + fib(4)) + (fib(5) + fib(4)) + (fib(4) + fib(3)) + (fib(5) + fib(4)) + (fib(4) + fib(3)) + (fib(4) + fib(3)) + (fib(3) + fib(2)) ... (this is getting quite enoying... 😅😅)
22nd Jun 2019, 5:58 PM
Anton Böhler
Anton Böhler - avatar
+ 1
thaks
22nd Jun 2019, 6:01 PM
Zakhar