Skip to content

Instantly share code, notes, and snippets.

@albertz
Created April 21, 2011 21:37
Show Gist options
  • Save albertz/935544 to your computer and use it in GitHub Desktop.
Save albertz/935544 to your computer and use it in GitHub Desktop.
memoization implementation with simple limit. some thoughs [here](http://www.az2000.de/docs/memoization/)
class Entry:
def __init__(self, x, y):
self.x = x
self.y = y
self.leftEntry = None
self.rightEntry = None
def pop(self):
if self.leftEntry is not None:
self.leftEntry.rightEntry = self.rightEntry
if self.rightEntry is not None:
self.rightEntry.leftEntry = self.leftEntry
self.leftEntry = None
self.rightEntry = None
class MemoizedFunction:
N = 100
def __init__(self, f):
self.f = f
self.entries = {}
self.topEntry = None
self.bottomEntry = None
def pushTop(self, entry):
entry.rightEntry = self.topEntry
if self.topEntry is not None:
self.topEntry.leftEntry = entry
self.topEntry = entry
if self.bottomEntry is None:
self.bottomEntry = entry
def __call__(self, x):
if x in self.entries:
entry = self.entries[x]
if entry is self.bottomEntry:
assert entry.rightEntry is None
self.bottomEntry = entry.leftEntry
entry.pop()
self.pushTop(entry)
return entry.y
y = self.f(x)
entry = Entry(x, y)
self.entries[x] = entry
self.pushTop(entry)
if len(self.entries) > self.N:
entry = self.bottomEntry
assert entry is not None
assert entry.rightEntry is None
assert entry.leftEntry is not None # at least for N>=2
del self.entries[entry.x]
self.bottomEntry = entry.leftEntry
self.bottomEntry.rightEntry = None
return y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment