0

How does ths code work? (i didn't understand) explain line by line.....

def fib(n): a = 1 b = 1 while a<n: result.append(a) tmp_var = b b = a+b a = tmp_var return result print(fib(10))

6th Mar 2018, 5:22 PM
Tincture
4 Respostas
+ 3
This is Fibonacci series, means each number is equals to the sum of the two before him. a(n+2)=a(n+1)+a(n) if you know Math series's(Recursion). so it starts with 1(default value entered) and then its 1+0=1 and 1+1=2 and 1+2=3 and 2+3=5 and so goes on... The codes works like this. result is probably a list which you're appending each time in the while loop(with a). then a Temp variable is equal to b. basically the a(n+1) in the math series example. then b gets a new value of a(which is a(n)+an(+1) which is b at that point of time. which means b is now a(n+2). then a gets a new value which is a(n+1) which will be a(n) in the next time we run the while loop. The n variable in this function means: Until which value in the series should we get to. Meaning if we enter n as 10 we will get every value of the Fibonacci series until 10.
6th Mar 2018, 5:55 PM
Tomer Sim
Tomer Sim - avatar
+ 2
What is result?
6th Mar 2018, 5:33 PM
Tomer Sim
Tomer Sim - avatar
+ 2
I have redone your code, changed tmp_var to c because of reasons. https://code.sololearn.com/cVX5e68ZL79e/#py
6th Mar 2018, 6:05 PM
Tomer Sim
Tomer Sim - avatar
0
well it wont for two reasons because 1) the return function is one space ahead and 2) you need to define the variable result
6th Mar 2018, 5:49 PM
Obbu
Obbu - avatar