Skip to content

Instantly share code, notes, and snippets.

@skatenerd
Last active August 29, 2015 14:20
Show Gist options
  • Save skatenerd/11df0e39676ee7f70625 to your computer and use it in GitHub Desktop.
Save skatenerd/11df0e39676ee7f70625 to your computer and use it in GitHub Desktop.
optimize
# Old implementation. Can you spot the optimization?
predicates = [lambda x: x.is_rad(), lambda x: x.is_cool(), lambda x: x.is_baller()]
all_products = Product.objects.all()
products = reduce(
lambda filtered_so_far, predicate: filter(predicate, filtered_so_far),
predicates,
all_products
)
# New implementation
def and_combinate(f,g):
return lambda x: f(x) and g(x)
predicates = [lambda x: x.is_rad(), lambda x: x.is_cool(), lambda x: x.is_baller()]
all_products = Product.objects.all()
combofilter = reduce(and_combinate, predicates)
products = filter(combofilter, all_products)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment