Created
May 6, 2020 21:00
-
-
Save wiccy46/11e90344823aae6bcefec3de2a68ed3e to your computer and use it in GitHub Desktop.
[memoization]Memoization decorator #python #optimization
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
class Memoize: | |
def __init__(self, func): | |
self.func = func | |
self.cache = {} | |
def __call__(self, arg): | |
if arg not in self.cache: | |
self.cache[arg] = self.func(arg) | |
return self.cache[arg] | |
@Memoize | |
def partition_func(n): | |
if n == 0: return 1 | |
result = 0; k = 1; sign = 1; | |
while True: | |
pent = (3*k**2 - k) // 2 | |
if pent > n: break | |
result += sign * partition_func(n - pent) | |
pent += k | |
if pent > n: break | |
result += sign * partition_func(n - pent) | |
k += 1; sign = -sign; | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment