Created
April 10, 2019 02:32
-
-
Save popunbom/ccf666ad2665e561f1dc6bef654788b0 to your computer and use it in GitHub Desktop.
デコレータを使ったメモ化サンプル (Python 3.6)
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
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| from sys import argv | |
| def memoize(func): | |
| memo = dict() | |
| def wrapper(*args, **kwargs): | |
| args_tuple = tuple(args) + tuple(kwargs.values()) | |
| if args_tuple in memo: | |
| ret_val = memo[args_tuple] | |
| else: | |
| ret_val = func(*args, **kwargs) | |
| memo[args_tuple] = ret_val | |
| return ret_val | |
| return wrapper | |
| @memoize | |
| def fib(n): | |
| if n in (0, 1): | |
| return n | |
| else: | |
| return fib(n-1) + fib(n-2) | |
| if __name__ == '__main__': | |
| argc = len(argv) | |
| if argc == 1: | |
| while True: | |
| N = int(input("N? > ")) | |
| print(f"fib({N}) = {fib(N)}") | |
| elif argc > 1: | |
| N = int(argv[1]) | |
| print(f"fib({N}) = {fib(N)}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment