2

I have written a script for Fibonacci series with single line variable assignment and multiple line variable assignment. I got two different results

Multiple lines:

class fibonacci:
    def fib(self,num):
      result = []
      a = 0
      b = 1
      while a < num:
          result.append(a)
          a = b
          b =  a + b
      return result

instance = fibonacci()
new_inst = instance.fib(100)
print new_inst

output:

[0, 1, 2, 4, 8, 16, 32, 64]

Order Changed:

class fibonacci:
    def fib(self,num):
      result = []
      b = 1
      a = 0
      while a < num:
          result.append(a)
          b = a + b
          a = b
      return result

instance = fibonacci()
new_inst = instance.fib(100)
print new_inst

Output:

[0, 1, 2, 4, 8, 16, 32, 64]

Single line:

class fibonacci:
    def fib(self,num):
      result = []
      a,b = 0,1
      while a < num:
          result.append(a)
          a,b = b, a + b
      return result

instance = fibonacci()
new_inst = instance.fib(100)
print new_inst

output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
user60679
  • 709
  • 14
  • 28

1 Answers1

3

The only difference is the order of evaluation. When you assign

a, b = b, a + b

The right-hand expressions are evaluated fully before assignment to the left hand side, so the order of evaluation is:

foo = a + b
bar = a
b = foo
a = bar

This is different to the order of evaluation in your first example, which is:

 a = b
 b =  a + b

Hence your two examples generate different results.

To work around your issue, I would probably use:

c = a
a = b
b = a + c

This generates the correct output as desired.

gtlambert
  • 11,711
  • 2
  • 30
  • 48
  • `class fibonacci: def fib(self,num): result = [] a,b = 0,1 while a < num: result.append(a) b = a + b a = b return result instance = fibonacci() new_inst = instance.fib(100) print new_inst` but still i got same output: [0, 1, 2, 4, 8, 16, 32, 64] – user60679 Oct 18 '15 at 10:33
  • I have changed the order but still I got the two different outputs – user60679 Oct 18 '15 at 10:35
  • but why should I use one more variable? – user60679 Oct 18 '15 at 11:02
  • You don't need to. Your 2nd example is correct. However, for clarity (and your understanding), my solution might be easier. – gtlambert Oct 18 '15 at 11:04