Created
August 18, 2016 17:57
-
-
Save c3h3/db37965838244b0ce36d0b36718d3901 to your computer and use it in GitHub Desktop.
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
## please run the following codes in ipython notebook or ipython shell | |
In [1]: fib = lambda n: 1 if n < 2 else fib(n-1) + fib(n-2) | |
In [2]: %tiem fib(35) | |
ERROR: Line magic function `%tiem` not found. | |
In [3]: %time fib(35) | |
CPU times: user 3.06 s, sys: 26.7 ms, total: 3.09 s | |
Wall time: 3.05 s | |
Out[3]: 14930352 | |
In [4]: def mem(f): | |
...: res = {} | |
...: def new_f(n): | |
...: if n not in res: | |
...: res[n] = f(n) | |
...: return res[n] | |
...: return new_f | |
...: | |
In [5]: fib = mem(fib) | |
In [6]: %time fib(35) | |
CPU times: user 3.33 ms, sys: 0 ns, total: 3.33 ms | |
Wall time: 130 µs | |
Out[6]: 14930352 | |
In [7]: @mem | |
...: def FIB(n): | |
...: return 1 if n < 2 else FIB(n-1) + FIB(n-2) | |
...: | |
In [8]: %time FIB(36) | |
CPU times: user 3.33 ms, sys: 0 ns, total: 3.33 ms | |
Wall time: 80.1 µs | |
Out[8]: 24157817 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment