Python Program To Generate Fibonacci Sequence

2 min read

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]

PROGRAMS

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read