Created
June 7, 2012 10:39
-
-
Save fumieval/2888115 to your computer and use it in GitHub Desktop.
Pythonでメモ化再帰
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
| class Memoize: | |
| """ | |
| Example usage: | |
| >>> @Memoize | |
| ... def fib(n): | |
| ... if n <= 1: | |
| ... return n | |
| ... else: | |
| ... return fib(n - 1) + fib(n - 2) | |
| >>> fib(300) | |
| 222232244629420445529739893461909967206666939096499764990979600L | |
| """ | |
| def __init__(self, f): | |
| self.f = f | |
| self.memo = {} | |
| def __call__(self, *args): | |
| if args in self.memo: | |
| return self.memo[args] | |
| else: | |
| result = self.f(*args) | |
| self.memo[args] = result | |
| return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment