Skip to content

Instantly share code, notes, and snippets.

@hyunjun
Last active August 29, 2015 14:23
Show Gist options
  • Save hyunjun/cae504f02fd8a0e140d8 to your computer and use it in GitHub Desktop.
Save hyunjun/cae504f02fd8a0e140d8 to your computer and use it in GitHub Desktop.
lru_cache
# http://www.quora.com/Isnt-dynamic-programming-much-simpler-coding-in-languages-like-Python-and-others-rather-than-Java-C-C++
# https://docs.python.org/3/library/functools.html
$ python3
Python 3.4.2 (default, Oct 19 2014, 17:52:17)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.51)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from functools import lru_cache
>>> @lru_cache(maxsize=None)
... def fib(n):
... if n < 2:
... return n
... return fib(n - 1) + fib(n - 2)
...
>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment