5

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
Rio
  • 765
  • 3
  • 17
  • 37
  • 6
    In second one, you are doing `b = 2*b` actually since `a = b`. – Lafexlos Apr 01 '16 at 15:43
  • 4
    It's because in the first case `a,b=b,a+b` happens simultaneously and in the second case firstly happens `a=b` and then `b = a+b` is essentially `b = b+b`. – Tony Babarino Apr 01 '16 at 15:44
  • As a side note, I will give you the benefit of the doubt and assume that your input, `n`, is NOT the number of fibonacci numbers you want printed. Rather it's all fibonacci numbers < `n`. – Dzhao Apr 01 '16 at 15:45

13 Answers13

8

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
Lafexlos
  • 7,618
  • 5
  • 38
  • 53
  • 1
    @IronFist BTW, what do you mean by _fix_? Use 4 spaces instead of 2? As long as I am consistent with the number of spaces, I don't think it should be _fixed_. – Lafexlos Apr 01 '16 at 16:05
  • According to PEP* (I don't remember what number it was)...Indentation should be 4 spaces...to conform with Coding Style Standard – Iron Fist Apr 01 '16 at 16:08
  • 1
    PEP-8 is a *recommendation*, which only code in the standard library is required to follow. There's no reason the code here *must* be indented 4 spaces per level, other than to make life easier for people copying it to paste into their own, 4-space-per-level code. – chepner Apr 01 '16 at 16:14
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
Alycs
  • 121
  • 1
2

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)
2

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)
1

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.

Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
0
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))
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
0
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
  • 2
    The question is seeking an explanation of what is going wrong. Please explain what is wrong with the code that is not working. – Harsh Wardhan Feb 10 '20 at 06:45
0

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))
0
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)
  • 1
    Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it answers the specific question being asked. See [answer]. – ChrisGPT was on strike Jul 29 '21 at 21:47
0
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 
0
# 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 = " ")
Manendar
  • 19
  • 3
0

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
David Leal
  • 6,373
  • 4
  • 29
  • 56
-1
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)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    Welcome to Stack Overflow. Please take the [tour]. SO isn't for sharing various implementations of code, it's for answering questions. OP asks why _their_ version doesn't work. A totally new implementation doesn't answer that question. – ChrisGPT was on strike Dec 09 '21 at 12:15