Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python fibonacci series

Tags:

python

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
like image 556
Rio Avatar asked Dec 07 '22 23:12

Rio


2 Answers

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
like image 20
Alycs Avatar answered Dec 29 '22 15:12

Alycs


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
like image 65
Lafexlos Avatar answered Dec 29 '22 14:12

Lafexlos