Skip to content

Instantly share code, notes, and snippets.

@AaronO
Created March 16, 2016 19:09
Show Gist options
  • Save AaronO/40a1ce591c65ff34f854 to your computer and use it in GitHub Desktop.
Save AaronO/40a1ce591c65ff34f854 to your computer and use it in GitHub Desktop.
# 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