Created
July 28, 2014 18:58
-
-
Save unutbu/351c04915e9876a581be to your computer and use it in GitHub Desktop.
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
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