Skip to content

Instantly share code, notes, and snippets.

@Ogaday
Created July 1, 2019 16:50
Show Gist options
  • Save Ogaday/9abe4df606b42b3942c113f35b704fdb to your computer and use it in GitHub Desktop.
Save Ogaday/9abe4df606b42b3942c113f35b704fdb to your computer and use it in GitHub Desktop.
Fibonacci Function
"""
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)}")
@Ogaday
Copy link
Author

Ogaday commented Jul 1, 2019

Wrote this while demoing coderpad.io - very happy with the platform so far!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment