Skip to content

Instantly share code, notes, and snippets.

@smarnach
Created February 28, 2012 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save smarnach/1934353 to your computer and use it in GitHub Desktop.
Save smarnach/1934353 to your computer and use it in GitHub Desktop.
import random
import timeit
def inter_reduce(sets):
return reduce(set.intersection, sets)
def inter_for(sets):
sets = iter(sets)
result = next(sets)
for s in sets:
result.intersection_update(s)
return result
random.seed(42)
sets = [set(random.randrange(1000) for i in range(4000))
for j in range(100)]
print timeit.timeit("inter_reduce(sets)",
"from __main__ import inter_reduce, sets", number=1000)
print timeit.timeit("inter_for(sets)",
"from __main__ import inter_for, sets", number=1000)
@pzelnip
Copy link

pzelnip commented Feb 28, 2012

^^ as an addendum to this, my fork has versions that are referentially transparent, but this definitely adds significant overhead (still cheaper than reduce though). I'm pretty sure there's a better way of doing it as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment