Skip to content

Instantly share code, notes, and snippets.

@wiccy46
Created May 6, 2020 21:00
Show Gist options
  • Save wiccy46/11e90344823aae6bcefec3de2a68ed3e to your computer and use it in GitHub Desktop.
Save wiccy46/11e90344823aae6bcefec3de2a68ed3e to your computer and use it in GitHub Desktop.
[memoization]Memoization decorator #python #optimization
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