-1

I have written two version of the program and new to python. I am not able to understand what went wrong while printing a Fibonacci series. The first program prints the Fibonacci series correctly but the second program has an issue. Please let me know what's wrong.

Program 1

def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

# Now call the function we just defined:
fib(2000)

Output

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

Program 2

# Let make a function that prints a Fibonacci 
def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a = 0
    b = 1
    while a < n:
        print(a, end=" ")
        a = b
        b = a+b
fib(2000)

Output

0 1 2 4 8 16 32 64 128 256 512 1024 
Jab
  • 26,853
  • 21
  • 75
  • 114
Shiv Kumar Ganesh
  • 3,799
  • 10
  • 46
  • 85

3 Answers3

3

The trick is in the line:

a, b = b, a+b

This assigns the value of b to a and assigns the value of a+b to b, but it does so before a is assigned its new value.

You replaced this with:

a = b
b = a+b

This changes a first and only then assigns a+b to b. If you'd want to do it like this you could do:

c = a+b
a = b
b = c

Or something similar, but I think the original solution is the cleaner one, although clearly not sufficiently intuitive, as it stumped you :)

Grismar
  • 27,561
  • 4
  • 31
  • 54
  • Got your point. Seems I was not able to catch the concept. Do you have some link pointing to this concept. – Shiv Kumar Ganesh Jan 30 '19 at 01:02
  • 1
    I don't have a specific link, but the concept is called 'tuple assignment' and it is often used to do tricks like swapping the values of two variables: `a, b = b, a`. Note how that's different from `a = b` and then `b = a`. Clearly, in the latter case, you'd end up with both variables having the same value. Note that your code combines 'tuple assignment' and Python's automatic unpacking of a tuple when required (so, it is unpacking the tuple that's created on the right, storing the components in the two variables on the left). – Grismar Jan 30 '19 at 01:04
0
a = b
b = a+b

is not the same as

a, b = b, a+b

In the first version: when first line is executed the old value of a is destroyed so the second line is equivalent to b = b+b

so at every iteration b is assigned to 2*b, hence the sequence 1,2,4,8...

sam46
  • 1,273
  • 9
  • 12
0

a, b = b, a+b is not the same as a = b; b = a+b. In particular the value of a is not the same when a+b is evaluated.