Skip to content

Instantly share code, notes, and snippets.

@philipaconrad
Created July 2, 2013 06:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipaconrad/5907155 to your computer and use it in GitHub Desktop.
Save philipaconrad/5907155 to your computer and use it in GitHub Desktop.
A near-exact port of Luke Gorrie's table data structure that "garbage collects" not-recently-used items in O(1) time. Find the original at: https://gist.github.com/lukego/4706097
class lukegoLRU:
def __init__(self):
# Initialize 'old' and 'new' to empty tables
self.old = {}
self.new = {}
def insert(k, v):
self.new[k] = v
def lookup(k):
if self.new.get(k):
# Found in new table
return self.new[k]
elif self.old.get(k):
# Migrate from old table to new table
self.new[k] = self.old[k]
return self.old[k]
else:
# Not found
return None
def age():
# Entries in 'old' are dropped, entries in 'new' become old.
self.old = self.new.copy()
self.new = {} # empty table
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment