Created
August 27, 2017 14:19
-
-
Save victor-iyi/140ecd5d622cf87f26fd371324ffd516 to your computer and use it in GitHub Desktop.
Explore 4 different implementations of Fibonacci algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### PROGRAMMING FIBONACCI NUMBERS FROM BEGINNER TO EXPERT | |
### Method: 1 | |
print('Method: 1') | |
def fibonacci(no): | |
series = [1,1] | |
for _ in range(1, no-1): | |
series.append(series[-1] + series[-2]) | |
return series | |
n_sequence = input('How many fibonacci numbers should I generate for you: ') | |
series = fibonacci(int(n_sequence)) | |
print(series) | |
### End of method 1 | |
print(70*'-', '\n') # For dividers and space | |
### Method: 2 | |
print('Method: 2') | |
def fib(no): | |
if no <=2: | |
return 1 | |
else: | |
return fib(no-1) + fib(no-2) | |
n_sequence = input('How many fibonacci numbers should I generate for you: ') | |
series = [fib(i) for i in range(1, int(n_sequence)+1)] | |
print(series) | |
### End of method 2 | |
print(70*'-', '\n') # For dividers(-------) and new line | |
### Method: 3 | |
print('Method: 3') | |
def fib(no): | |
if no <= 2: | |
f = 1 | |
else: | |
f = fib(no-1) + fib(no-2) | |
return f | |
n_sequence = input('How many fibonacci numbers should I generate for you: ') | |
series = [fib(i) for i in range(1, int(n_sequence)+1)] | |
print(series) | |
### End of method 3 | |
print(70*'-', '\n') # For dividers and space | |
# Method: 4 [THE MOST OPTIMIAL METHOD] BUT Creepiest | |
memo = {} | |
def fib(no): | |
if no in memo: | |
return memo[no] | |
if no <= 2: | |
f = 1 | |
else: | |
f = fib(no-1) + fib(no-2) | |
memo[no] = f | |
return f | |
n_sequence = input('How many fibonacci numbers should I generate for you: ') | |
series = [fib(i) for i in range(1, int(n_sequence)+1)] | |
print(series) | |
### End of method 4 | |
print(70*'-', '\n') # For dividers and space |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment