Skip to content

Instantly share code, notes, and snippets.

@unutbu
Created July 28, 2014 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unutbu/351c04915e9876a581be to your computer and use it in GitHub Desktop.
Save unutbu/351c04915e9876a581be to your computer and use it in GitHub Desktop.
def memo(f):
"""Decorator that caches the return value for each call to f(args).
Then when called again with same args, we can just look it up."""
cache = {}
def _f(*args):
try:
return cache[args]
except KeyError:
cache[args] = result = f(*args)
return result
except TypeError:
# some element of args can't be a dict key
return f(*args)
_f.cache = cache
return _f
@memo
def best_strategy(time_remaining, wealth, income):
if time_remaining < 6:
# Best to just hold
return wealth
else:
# Could hold or invest
return max(best_strategy(time_remaining-6, wealth+income, income),
best_strategy(time_remaining-6, wealth-25+income, income+1))
print(best_strategy(210, 650, 250))
# 9445
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment