Last active
August 21, 2020 12:16
-
-
Save arlyon/81761f01165fa73b262cf5540cfc818e to your computer and use it in GitHub Desktop.
A nice little memoization decorator.
This file contains 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
from typing import Callable | |
def memoize(func: Callable) -> Callable: | |
solutions = {} | |
def new_func(*n): | |
if n not in solutions: | |
solutions[n] = func(*n) | |
return solutions[n] | |
return new_func | |
@memoize | |
def fib(n): | |
if n == 1 or n == 2: | |
return 1 | |
else: | |
return fib(n - 1) + fib(n - 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment