|
""" |
|
get(): O(1) |
|
it's an access to a hash table(dict in python) |
|
|
|
put(): O(n) |
|
O(1) while current size of the cache is smaller than the capacity of the cache |
|
worest case is O(n) since it have to calculate the score for all data (n) |
|
""" |
|
import time |
|
import math |
|
|
|
class Cache: |
|
def __init__(self, maxSize): |
|
self.maxSize = maxSize |
|
self.size = 0 |
|
self.data = {} |
|
self.lastAccessTime = {} |
|
self.weight = {} |
|
|
|
def get(self, key): |
|
self.lastAccessTime[key] = time.time() |
|
return self.data[key] if key in self.data else -1 |
|
|
|
def getLeastScoreKey(self): |
|
scores = {} |
|
currentTime = time.time() |
|
for key in self.data.keys(): |
|
lastAccessTime = self.lastAccessTime[key] |
|
weight = self.weight[key] |
|
|
|
if(currentTime != lastAccessTime): |
|
scores[key] = (weight/math.log(currentTime - lastAccessTime)) |
|
else: |
|
scores[key] = weight/-100 |
|
return min(scores, key=scores.get) |
|
|
|
def put(self, key, value, weight): |
|
if(self.size < self.maxSize): |
|
self.size += 1 |
|
else: |
|
leastScoreKey = self.getLeastScoreKey() |
|
del self.data[leastScoreKey] |
|
del self.weight[leastScoreKey] |
|
del self.lastAccessTime[leastScoreKey] |
|
self.data[key] = value |
|
self.weight[key] = weight |
|
self.lastAccessTime[key] = time.time() |
|
|
|
cache = Cache(3) |
|
cache.put('go', 1, 1) |
|
cache.put('goagain', 2, 100) |
|
cache.put('goagain2', 3, 100) |
|
print(cache.get('go')) |
|
cache.put('goagain3', 4, 100) |
|
print(cache.get('go'), cache.get('goagain'), cache.get('goagain2'), cache.get('goagain3')) |