View This Site In Your Own Language

Fibonacci Series

fibonacci series
In [14]:
12import time

Using FormulaΒΆ

Formula is the best way to reduce complexity of code.

fibonacci_formula.gif

In [1]:
123def fibonacci(n):
    return int(((1 + 5**0.5)**n - (1 - 5**0.5)**n)/(2**n * 5**0.5))
In [2]:
12print(fibonacci(10))
1255

Using loopsΒΆ

Way 1ΒΆ
In [17]:
123456789101112start = time.time()

f1, f2 = 1, 1

# to get the first 10 elements in fibonacci series
for _ in range(10):
    print(f1, end=' ')
    f1, f2 = f2, f1+f2
    
end = time.time()
print('\nCode execution time : ', end - start)
1231 1 2 3 5 8 13 21 34 55 
Code execution time :  0.004085063934326172
Way 2ΒΆ

*** Use this method

In [4]:
1234567891011# you may use list to store the values

fib, f1, f2 = [], 1, 1

# to get the first 10 elements in fibonacci series
for i in range(10):
    fib.append(f1)
    f1, f2 = f2, f1+f2
    
print(fib)
12[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Way 3ΒΆ
In [5]:
1234567def fibonacci(n):
    fib = [1, 1]
    
    for i in range(2, n):  
        fib.append(fib[-1] + fib[-2])
    return fib
In [6]:
12print(fibonacci(10))
12[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Using Recursive functionΒΆ

In [7]:
123456def fibonacci(n):
    if n<2:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)
In [8]:
123# fibonacci should return (n+1)th element from fibonacci series
print(fibonacci(10))
1289

Using yield generatorΒΆ

In [9]:
1234567def fibonacci():
    f1, f2 = 1, 1

    while True:
        yield f1
        f1, f2 = f2, f1+f2
In [10]:
123456# fibonacci() should print until element less than condition
for element in fibonacci():
    if element > 100:
        break
    print(element, end=' ')
11 1 2 3 5 8 13 21 34 55 89 
In [11]:
12345678fib = []

for element in fibonacci():
    if element > 100:
        break
    fib.append(element)
print(fib)
12[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [12]:
123for index, element in zip(range(10), fibonacci()):
     print('{}th element : {}'.format(index+1, element))
12345678910111th element : 1
2th element : 1
3th element : 2
4th element : 3
5th element : 5
6th element : 8
7th element : 13
8th element : 21
9th element : 34
10th element : 55
Fibonacci Series Fibonacci Series Reviewed by Ikram on 7/15/2021 04:05:00 AM Rating: 5

No comments:

Powered by Blogger.