Created
August 20, 2013 18:40
-
-
Save thomasballinger/6285452 to your computer and use it in GitHub Desktop.
Caching, overloading __getitem__ etc, memoization
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
import pickle | |
import glob | |
cache = {} | |
def fib(x): | |
if x in cache: | |
return cache[x] | |
if x < 2: return 1 | |
r = fib(x-1) + fib(x-2) | |
cache[x] = r | |
return r | |
print fib(32) | |
class LessMemoryDict(object): | |
def __init__(self): | |
pass | |
def __getitem__(self, item): | |
print 'getting item', item | |
try: | |
with open('lmd_'+item, 'r') as f: | |
return pickle.load(f) | |
except IOError: | |
raise KeyError | |
def __setitem__(self, item, value): | |
print 'setting item', item, 'to', value | |
with open('lmd_'+item, 'w') as f: | |
pickle.dump(value, f) | |
def __repr__(self): | |
return repr("<LessMemoryDict object with stuff that would take too long to look up>") | |
def __len__(self): | |
return len(glob.glob('lmd_*')) | |
t = LessMemoryDict() | |
t['a'] = 'asdf' | |
print t['a'] | |
print len(t) | |
print t | |
print t['b'] | |
t['dog']['perro'] = .4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment