Thursday 1 January 2015

Fibonacci Sequence

Question: Fibonacci sequence starts from 0,1 and their sum is 1 and the sum of 1,1 is 2 and this continues. See the picture and you will understand:

In the similar way using python generate first 15 Fibonacci numbers.

Answer: I have used functional approach. If you don't know what functions are, then remove the first line with def fibanocci(n): and then instead of n add the number of Fibonacci numbers you want. This will give you the result. But I suggest you to use functions as you write the code once and generate the output the required times. You can even test your answer with the question example(if given). I wrote the code such that it will be easy to understand, but if you don't understand please do ask me I will explain. Also post your Fibonacci code.


#Function to generate n fibanocci numbers
def fibanocci(n):
        a = 0
        b = 1
        numbers = []
        numbers.append(a)
        while len(numbers) < n+2:
                numbers.append(b)
                temp = a
                a = b
                b = a+temp
        return numbers
print fibonacci(15)
Output:

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

No comments:

Post a Comment