Skip to content

Instantly share code, notes, and snippets.

@wpcarro
Created April 6, 2024 18:24
Show Gist options
  • Save wpcarro/65df6902cf5811181c2cf79868527012 to your computer and use it in GitHub Desktop.
Save wpcarro/65df6902cf5811181c2cf79868527012 to your computer and use it in GitHub Desktop.
Create an LRU cache with sized elements.
from collections import OrderedDict # this is awesome
class LRU(object):
def __init__(self, capacity: int):
self.capacity = capacity
self.xs = OrderedDict()
def __repr__(self):
return f"; ".join(f"{k}: {v[0]} ({v[1]})" for k, v in self.xs.items())
def rem(self):
return self.capacity - sum(v[1] for k, v in self.xs.items())
def insert(self, key: str, val: any, size: int):
if size > self.capacity:
raise Exception("Item too big")
evicted = []
while self.rem() < size:
evicted.append(self.xs.popitem(last=False))
self.xs[key] = (val, size)
return evicted
def get(self, key: str):
if key in self.xs:
val = self.xs.pop(key=key)
self.xs[key] = val
return val
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment