Last active
April 12, 2025 17:35
-
-
Save danbednarski/d35a4b219e83df789547db4586a0286d to your computer and use it in GitHub Desktop.
Comparing simple handrolled memoization to @cache decorator from functools
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
# curiosity piqued by this note: https://substack.com/@pythonclcoding/note/c-107253391 | |
from functools import cache | |
@cache | |
def fib_cache(n): | |
if n <= 1: | |
return n | |
return fib_cache(n-1)+fib_cache(n-2) | |
my_cache = {} | |
def fib_memo(n): | |
if n <= 1: | |
return n | |
if n in my_cache: | |
return my_cache[n] | |
fib_n = fib_memo(n-1)+fib_memo(n-2) | |
my_cache[n] = fib_n | |
return fib_n |
Author
danbednarski
commented
Apr 12, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment