Created
July 1, 2019 16:50
-
-
Save Ogaday/9abe4df606b42b3942c113f35b704fdb to your computer and use it in GitHub Desktop.
Fibonacci Function
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
""" | |
Implementation of a function that returns elements from the Fibonacci sequence using DP | |
https://en.wikipedia.org/wiki/Fibonacci_number | |
https://en.wikipedia.org/wiki/Dynamic_programming | |
""" | |
import logging | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.INFO) | |
sh = logging.StreamHandler() | |
sh.setLevel(logging.INFO) | |
logger.addHandler(sh) | |
# Our cache for DP | |
memory = { | |
0: 0, | |
1: 1 | |
} | |
def fib(n): | |
""" | |
Calculate the nth Fibonacci number. | |
Memoizes fibonacci numbers for later reuse. | |
""" | |
logger.info(f"Calculating fib({n})") | |
try: | |
logger.info(f"Looking up fib({n}) in memory...") | |
memory[n] | |
logger.info(f"Found fib({n}) in cache!") | |
except KeyError: | |
logger.info(f"fib({n}) has not yet been memoized. Caching the result now.") | |
memory[n] = fib(n-1) + fib(n-2) | |
logger.info(f"Returning fib({n})") | |
return memory[n] | |
if __name__ == "__main__": | |
for i in range(11): | |
print(f"fib({i}) = {fib(i)}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wrote this while demoing coderpad.io - very happy with the platform so far!