I wrote a Fibonacci series using Python. Could not figure out why second program is giving wrong answer and first one right when both look same.
Below program gives right answer
def fib(n):
a,b=0,1
while b<n:
print b
a,b=b,a+b
fib(4)
1
1
2
3
Below program gives wrong answer:
def fib(n):
a = 0
b = 1
while b<n:
print b
a = b
b = a+b
fib(4)
1
2
In the second code posted, you redefine the value of b after having changed a, resulting as
def fib(n):
a = 0
b = 1
while b<n:
print b #prints 1
a = b #a = 1
b = a+b #b = 1 + 1 = 2
In the second code, there is no problem, as python code generally reads equations from right to left, thus redefines b first, as is correct
def fib(n):
a,b=0,1 #a = 0, b = 1
while b<n:
print b
a,b=b,a+b #b = 0 + 1 = 1, #a = 1
In first one, a, b = b, a+b
does the assigning simultanously.
In second one, you are first doing a = b
and then doing b = a+b
which actually is just b = 2*b
.
How to achieve such behaviour in second one? Use temporary value to store a
.
def fib(n):
a = 0
b = 1
while b<n:
print b
temp = a
a = b
b = temp+b
fib(4)
>>>1
>>>1
>>>2
>>>3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With