Created
August 10, 2014 10:01
-
-
Save selfboot/99f59f1b4cf8fb8c08eb to your computer and use it in GitHub Desktop.
Revisions
-
selfboot revised this gist
Aug 10, 2014 . 1 changed file with 5 additions and 0 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -41,3 +41,8 @@ def fib_cache(n): print t1.timeit(100000) print t2.timeit(100000) """ 1.71311998367 0.0279998779297 """ -
selfboot created this gist
Aug 10, 2014 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,43 @@ #! /usr/bin/env python # -*- coding: utf-8 -*- from functools import wraps def fib_direct(n): assert n > 0, 'invalid n' if n < 3: return n else: return fib_direct(n - 1) + fib_direct(n - 2) def cache(func): caches = {} @wraps(func) def wrap(*args): if args not in caches: caches[args] = func(*args) return caches[args] return wrap @cache def fib_cache(n): assert n > 0, 'invalid n' if n < 3: return 1 else: return fib_cache(n - 1) + fib_cache(n - 2) if __name__ == "__main__": from timeit import Timer t1 = Timer("fib_direct(10)", "from __main__ import fib_direct") t2 = Timer("fib_cache(10)", "from __main__ import fib_cache") print t1.timeit(100000) print t2.timeit(100000)