Last active
February 8, 2020 00:28
-
-
Save r3gor/3d37b3e537515f5cd1b3a7b631cb5ae4 to your computer and use it in GitHub Desktop.
Testing performance fibonacci function with Dynamic Programming
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
""" Performance fibonacci function with Dynamic Programming """ | |
import time | |
def fib1(n): | |
""" simple recursive algorithm """ | |
if (n == 1 or n == 2): | |
return 1 | |
return fib1(n-1) + fib1(n-2) | |
memory_fib2 = {} | |
def fib2(n): | |
""" D.P. = recursive + memorization """ | |
if n in memory_fib2: | |
return memory_fib2[n] | |
if (n == 1 or n == 2): | |
return 1 | |
elif (n>2): | |
memory_fib2[n] = fib2(n-1) + fib2(n-2) | |
return memory_fib2[n] | |
if __name__ == "__main__": | |
# TESTING | |
print("\n\n TEST fib1 ") | |
for n in range(30,40): | |
i = time.time() | |
valor = fib1(n) | |
f = time.time() | |
print(" fib({:2}) = {:<9}| time for calculating: {:6}".format(n, valor, round(f-i,7))) | |
print("\n\n TEST fib2() ") | |
for n in range(30,40): | |
i = time.time() | |
valor = fib2(n) | |
f = time.time() | |
print(" fib({:2}) = {:<9}| time for calculating: {:6}".format(n, valor, f-i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment