Skip to content

Instantly share code, notes, and snippets.

@accessnash
Created December 7, 2020 10:32
Show Gist options
  • Save accessnash/72fbd76e213ba57de93ddbfba1975efa to your computer and use it in GitHub Desktop.
Save accessnash/72fbd76e213ba57de93ddbfba1975efa to your computer and use it in GitHub Desktop.
3 different ways of using caching for a simple computation of Fibonacci numbers. Also using lru_cache (Least recently used) in Python to limit the number of items in cache
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 7 10:35:31 2020
@author: Localuser
"""
# 1st method using a Class
class Fib:
def __init__(self):
self.cache = {1: 1, 2: 1}
def fibonacci(self, n):
if n not in self.cache:
print('Calculating fibonacci({0})'.format(n))
self.cache[n] = self.fibonacci(n-1) + self.fibonacci(n-2)
return self.cache[n]
# 2nd method using a Closure
def fib():
cache = {1: 1, 2: 1}
def calc_fib(n):
if n not in cache:
print('Calculating fib({0})'.format(n))
cache[n] = calc_fib(n-1) + calc_fib(n-2)
return cache[n]
return calc_fib
# 3rd method using a Decorator
def memoize_fib(fib):
cache = dict()
def inner(n):
if n not in cache:
cache[n] = fib(n)
return cache[n]
return inner
@memoize_fib
def fib(n):
print('Calculating fib({0})'.format(n))
return 1 if n < 3 else fib(n-1) + fib(n-2)
#Using least recently used cache function in Python to limit the no. of items in cache
from functools import lru_cache
@lru_cache(maxsize = 16) # by default lru_cache has size of 128 items
def fib(n):
print('Calculating fib({0})'.format(n))
return 1 if n < 3 else fib(n-1) + fib(n-2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment