Python fibonacci series

Question:

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
Asked By: Rio

||

Answers:

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
Answered By: Lafexlos

In the first example, you’ve used this code:

a,b=b,a+b

While in the second, you’ve done this instead:

a = b
b = a+b

These are not the same thing.

For the sake of argument, let’s say that a = 3 and b = 6. Let’s run the working code first:

>>> a, b = 10, a + 1
>>> a
10
>>> b
4

The value of a + 1 is 4 rather than 11, because b‘s assignment is using the old value of a, so 3 + 1 == 4.

Now let’s put a and b back to their starting values. Let’s try the other method of assigning:

>>> a = 10
>>> b = a + 1
>>> a
10
>>> b
11

Now b is 11! That’s because a was assigned before the assignment of b, so the addition uses a‘s new value.

The reason your second version isn’t working is because the assignments don’t happen simultaneously, so b is actually 2 * b because a has already been set to b by the time a+b is executed.

Answered By: Aaron Christiansen

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
Answered By: Alycs
def fibonacci (n):
    if n == 1 or n == 2:
        return 1
    return fibonacci (n-1) + fibonacci (n-2)

for i in range(1,50):
    print (fibonacci(i))
Answered By: KleeWai Bot
n1 = 0
n2 = 1
c = 0

nTerms = int(input())

if nTerms <= 0:
    print("Enter the valid value")
elif nTerms == 1:
    print(a)
else:
    while c < nTerms:
        print(n1)
        nth = n1 + n2
        n1 = n2
        n2 = nth
        c += 1
Answered By: Lokesh Singh Sodha

Fibonacci Series Using Recursion

def f_recursion(n):
    if n <= 1:
        return n
    else:
        return(f_recursion(n-1) + f_recursion(n-2))
# Driver Code
nterms = int(input())
if nterms <= 0:
    print("Enter the positive value")
else:
    for i in range(0,nterms):
        print (f_recursion(i))
Answered By: Lokesh Singh Sodha

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)
Answered By: shivam sharma

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)
Answered By: shivam sharma
n1=int(input("Enter Term"))
mylist=[0,1]
for a in range(n1):
    sum=0
    for b in mylist[len(mylist)-2:]:
        sum+=b
    mylist.append(sum)
print(mylist)
Answered By: Coder119872
def fib(n1, n2):
    print(n1)
    print(n2)
    for i in range(n1, n2):
        n1 += n2
        n2 += n1
        print(n1)
        print(n2)

starting_number = int(input('Enter First Term: '))
ending_number = int(input('Enter Second Number: '))
fib(starting_number, ending_number)
Answered By: user17635520
def fib(n):
    a=0
    b=1
    sum=0
    for i in range(0,n):
        print(sum)
        sum = a + b 
        b = a
        a = sum
fib(10) // here you can add any n value from 1 to 100 
Answered By: Prathamesh Doshi
# The below code will generate the fibonacci series as per desired range
# just put the number, you want the fibonaci series upto.

def fibonacci(num):
    x,y = 0,1
    if num==1:
        print(x)
    elif num==2:
        print(x,y)
    else:
        print(x,y,end = " ")
        for i in range(num-2):
            z=x+y
            x=y
            y=z
            print(z,end = " ")
Answered By: Manendar

You can try the following simple approach based on the simplified version of the Binet formula:

F(n) = (((1+SQRT(5))/2)^n)/SQRT(5)

which can be expressed in Python as follows:

import math
def fibo(n):
    return (round((((1+math.sqrt(5))/2)**n)/math.sqrt(5),0))

and to return the series for the first 10 Fibonacci numbers:

print([int(fibo(n)) for n in range(1,11)])

The following is an efficient way to generate a Fibonacci series:

def fib_seq(n):
    seq = [1,1]
    for i in range(2, n):
        seq.append(seq[-1] + seq[-2])
    return 1 if n <= 1 else seq

Here is the output
output

Note: Based on the following post: Efficient calculation of Fibonacci series. Python starting from Fibonacci number 72, the first formula doesn’t provide the correct result (probably related to Python numeric precision, because testing in Excel gives the correct result). Then the following formula can be used:

def fibo(n):
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
    return a
Answered By: David Leal
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.