Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding the Fibonacci Sequence example in Python's function tutorial

This is what they have:

def fib(n):
    a, b = 0, 1
    while a < n:
        print a,
        a, b = b, a+b

This is what I have:

def fib(n):
    a = 0
    b = 1
    while a < n:
        print a
        a = b
        b = b+a

The first returns the correct sequence when employed, whereas mine proceeds 0, 1, 2, 4, 8, 16, 32...

I am currently learning programming (no prior computer science education), and it's clear that the problem is how I've defined my variables. What is the difference between separating the variables by commas and separating variables by a new line (assuming that is the issue)?

like image 780
user2189389 Avatar asked Mar 20 '13 05:03

user2189389


People also ask

What is Fibonacci series in Python example?

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.

What is Fibonacci sequence explain in detail with example?

The Fibonacci sequence is a series of numbers in which each number is the sum of the two that precede it. Starting at 0 and 1, the sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on forever. The Fibonacci sequence can be described using a mathematical equation: Xn+2= Xn+1 + Xn.

Does Python have a Fibonacci sequence?

Fibonacci Sequence can be implemented both iteratively and recursively in Python. For both examples, try changing the value of the argument passed to the function to print out more numbers in the sequence.


1 Answers

This is a tuple assignment:

a, b = 0, 1

You can also think of it as

(a, b) = (0, 1)

A temporary tuple is created with the values 0, and 1 and then unpacked onto the variable a and b

This is also a tuple assignment

a, b = b, a+b

Again, you can think of it as

(a, b) = (b, a+b)

The temporary tuple is created from the values of b and a+b before either of them is updated. The assignment only happens after the temporary tuple is created.

By breaking it out to separate steps, you are changing the meaning of the code.

Lets see what happens here

a, b = 0, 1        # a=0 , b=1
a, b = b, a+b      # a=1 , b=1

Compare with

a = 0              # a=0
b = 1              # a=0 , b=1
a = b              # a=1 , b=1
b = b+a            # a=1 , b=2 
like image 196
John La Rooy Avatar answered Nov 03 '22 05:11

John La Rooy