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
author's image
Abhijeet Pal Author and Editor in Chief @djangocentral

Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.

LinkedIn Twitter Github

Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - https://github.com/django/django/pull/14843 The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read