Skip to content

Instantly share code, notes, and snippets.

@victor-iyi
Created August 27, 2017 14:19
Show Gist options
  • Save victor-iyi/140ecd5d622cf87f26fd371324ffd516 to your computer and use it in GitHub Desktop.
Save victor-iyi/140ecd5d622cf87f26fd371324ffd516 to your computer and use it in GitHub Desktop.
Explore 4 different implementations of Fibonacci algorithm
### 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