Python Program To Generate Fibonacci Sequence

Problem Definition

Make a Python function for generating a Fibonacci sequence. The Fibonacci sequence is a series where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence is 0 followed by 1.

Example Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21

Solution

The beauty of Python is that there is always more than one way to tackle the same problem in this article we will go over some of the best methods to generate Fibonacci series in Python.

Method 1: Fibonacci Sequence Using Recursion

n = input('Enter the number of terms')
def fibo(n):
    if n <= 1:
       return n
    else:
       return(fibo(n-1) + fibo(n-2))

for i in range(int(n)):
    print(fibo(i), end=' ')

Output:

Enter the number of terms 6 
 0 1 1 2 3 5

Method 2: Fibonacci Sequence Using For Loop

n = int(input('Enter the number of terms'))

def Fibonacci(n):
    f0, f1 = 0, 1
    for _ in range(n):
        yield f0
        f0, f1 = f1, f0+f1

fibs = list(Fibonacci(n))
print(fibs)    

Output:

Enter the number of terms 6 
[0, 1, 1, 2, 3, 5]

Method 3: Fibonacci Sequence Using Lambda and Reduce

from functools import reduce

n = int(input('Enter the Number of terms'))
def fib(n):
    return reduce(lambda x, _: x+[x[-1]+x[-2]], range(n-2), [0, 1])
print(fib(n))

Output:

Enter the Number of terms 6
[0, 1, 1, 2, 3, 5]

Method 4: Fibonacci Sequence using lambda and map function

n = int(input('Enter the Number of terms'))

def fibonacci(count):
    fib_list = [0, 1]
    any(map(lambda _: fib_list.append(sum(fib_list[-2:])),
            range(2, count)))
    return fib_list[:count]

print(fibonacci(n))

Output:

Enter the Number of terms 6
[0, 1, 1, 2, 3, 5]

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close