Python fibonacci series
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
Solution 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
Solution 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
Solution 3:
fibonacci series using lambda function in python
n = int(input("Enter the range of numbers in fibonacci series:"))
F = [0,1]
list(map(lambda i: F.append(F[i-1] + F[i-2]), range(2, n)))
print(F)
Solution 4:
fibonacci series using List Comprehension function in python
n = int(input("Enter the range of numbers in fibonacci series:"))
F = [0,1]
[F.append(F[i-1] + F[i-2]) for i in range(2,n)]
print(F)