Created
July 2, 2013 06:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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