Skip to content

Instantly share code, notes, and snippets.

@smarnach
Created February 28, 2012 18:52
Show Gist options
  • 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

Very nice, one thing to note about this version though is that it does modify the 1st element of the list (the function is not referentially transparent). Print out the value of sets[0] before and after the call to inter_for. Easy enough to fix, just a thought.

@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