Created
March 16, 2016 19:09
-
-
Save AaronO/40a1ce591c65ff34f854 to your computer and use it in GitHub Desktop.
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
# hash returns a string representation of a function's arguments | |
# so that we can use that as a key | |
def hash(args): | |
return ":".join(map(str, args)) | |
def memoize(fn): | |
cache = {} | |
def memoized_fn(*args): | |
hashed = hash(args) | |
if hashed in cache: | |
return cache[hashed] | |
ret = fn(*args) | |
cache[hashed] = ret | |
return cache[hashed] | |
# Return wrapped function | |
return memoized_fn | |
@memoize | |
def get_url_title(url): | |
# Fake slow network connection | |
time.sleep(1.5) | |
return "Awesome title: %s" % url | |
@memoize | |
def recursive_fib(n): | |
# 0 -> 0 and 1 -> 1 | |
if n < 2: | |
return n | |
return recursive_fib(n-1) + recursive_fib(n-2) | |
recursive_fib(200) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment