Skip to content

Instantly share code, notes, and snippets.

@popunbom
Created April 10, 2019 02:32
Show Gist options
  • Select an option

  • Save popunbom/ccf666ad2665e561f1dc6bef654788b0 to your computer and use it in GitHub Desktop.

Select an option

Save popunbom/ccf666ad2665e561f1dc6bef654788b0 to your computer and use it in GitHub Desktop.
デコレータを使ったメモ化サンプル (Python 3.6)
#!/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