Skip to content

Instantly share code, notes, and snippets.

@dtaivpp
Last active October 31, 2019 14:21
Show Gist options
  • Save dtaivpp/f43673362f7c7fce53bec1623a01583b to your computer and use it in GitHub Desktop.
Save dtaivpp/f43673362f7c7fce53bec1623a01583b to your computer and use it in GitHub Desktop.
List comprehension with memoization example from https://stackoverflow.com/a/15812933/4577237
def memoize(f):
""" Memoization decorator for functions taking one or more arguments. """
class memodict(dict):
def __init__(self, f):
self.f = f
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.f(*key)
return ret
return memodict(f)
# Initialize global function call variable
funcRuns = 0
# Wrap function in memoization wrapper
@memoize
def f(x):
global funcRuns
# Increment funcRuns every time the function is run
funcRuns += 1
return True
# Initialize numbers list
nums = [0,1,2,3,4,4]
# Run the list comprehension with 2 calls to f(x) per iteration
# with 6 elements in the list and 2 calls per iteration this would
# normally yield 12 fuction executions.
[f(x) for x in nums if f(x)]
# Log number of f(x) runs
print(funcRuns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment