Created
March 21, 2011 22:23
-
-
Save stephenroller/880354 to your computer and use it in GitHub Desktop.
A generic dynamic programming decorator.
This file contains hidden or 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
#!/usr/bin/env python | |
# Generic Dynamic Programming Library | |
# Just throw @dynamic in front of any method | |
# to make it dynamic! | |
import hashlib | |
def dynamic(func): | |
vals = {} | |
def _dyn_func(*args, **kwargs): | |
hashish = [] | |
for arg in args: | |
hashish.append(hash(arg)) | |
for k,v in kwargs.iteritems(): | |
hash.append(hash(k)) | |
hash.append(hash(v)) | |
hashish_s = ''.join(str(h) for h in hashish) | |
hash_s = hashlib.sha256(hashish_s).hexdigest() | |
if hash_s in vals: | |
return vals[hash_s] | |
else: | |
value = func(*args, **kwargs) | |
vals[hash_s] = value | |
return value | |
return _dyn_func | |
@dynamic | |
def fib(n): | |
print "called on %d" % n | |
if n == 0 or n == 1: | |
return 1 | |
else: | |
return fib(n-1) + fib(n-2) | |
print fib(22) | |
# OUTPUT: | |
# called on 22 | |
# called on 21 | |
# called on 20 | |
# called on 19 | |
# called on 18 | |
# called on 17 | |
# called on 16 | |
# called on 15 | |
# called on 14 | |
# called on 13 | |
# called on 12 | |
# called on 11 | |
# called on 10 | |
# called on 9 | |
# called on 8 | |
# called on 7 | |
# called on 6 | |
# called on 5 | |
# called on 4 | |
# called on 3 | |
# called on 2 | |
# called on 1 | |
# called on 0 | |
# 28657 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment