Skip to content

Instantly share code, notes, and snippets.

@this-is-richard
Last active September 20, 2022 21:13
Show Gist options
  • Save this-is-richard/af1f6d78d0628603f5462ec1d8b53eca to your computer and use it in GitHub Desktop.
Save this-is-richard/af1f6d78d0628603f5462ec1d8b53eca to your computer and use it in GitHub Desktop.
import datetime
import math
class Node:
def __init__(self, key, value, weight, lastAccess):
self.key = key
self.value = value
self.weight = weight
self.lastAccess = lastAccess
def __str__(self):
return '{}, {}, {}, lastAccess'.format(self.key, self.value, self.weight, self.lastAccess)
class Cache:
def __init__(self, capacity=4):
self.__itemKeys = []
self.__hashMap = {}
self.__capacity = capacity
def __now(self):
return datetime.datetime.now()
def get(self, key):
try:
node = self.__hashMap[key]
node.lastAccess = self.__now()
return node.value
except KeyError:
return -1
def put(self, key, value, weight):
newNode = Node(key, value, weight, self.__now())
self.__hashMap[newNode.key] = newNode
self.__itemKeys.append(newNode.key)
if len(self.__itemKeys) > self.__capacity:
self.__handleExcess()
def __handleExcess(self):
self.__sortItems()
droppedKey = self.__itemKeys.pop()
del self.__hashMap[droppedKey]
def __sortItems(self):
self.__itemKeys.sort(key=self.__getScore, reverse=True)
def __getScore(self, key):
node = self.__hashMap[key]
return node.weight / math.log(self.__now - node.lastAccess)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment