Skip to content

Instantly share code, notes, and snippets.

@pzelnip
Forked from smarnach/gist:1934353
Created February 28, 2012 19:31
Show Gist options
  • Save pzelnip/1934583 to your computer and use it in GitHub Desktop.
Save pzelnip/1934583 to your computer and use it in GitHub Desktop.
import random
import timeit
from copy import deepcopy
def inter_reduce(sets):
return reduce(set.intersection, sets)
def inter_for_deepcopy(sets):
sets = iter(sets)
result = deepcopy(next(sets))
for s in sets:
result.intersection_update(s)
return result
def inter_for_copy(sets):
sets = iter(sets)
result = next(sets).copy()
for s in sets:
result.intersection_update(s)
return result
def inter_for_union(sets):
sets = iter(sets)
result = set().union(next(sets))
for s in sets:
result.intersection_update(s)
return result
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 len(sets[0])
print "inter_reduce: %s" % timeit.timeit("inter_reduce(sets)",
"from __main__ import inter_reduce, sets", number=1000)
print len(sets[0])
print "inter_for_deepcopy: %s" % timeit.timeit("inter_for_deepcopy(sets)",
"from __main__ import inter_for_deepcopy, sets", number=1000)
print len(sets[0])
print "inter_for_union: %s" % timeit.timeit("inter_for_union(sets)",
"from __main__ import inter_for_union, sets", number=1000)
print len(sets[0])
print "inter_for_copy: %s" % timeit.timeit("inter_for_copy(sets)",
"from __main__ import inter_for_copy, sets", number=1000)
print len(sets[0])
print "inter_for: %s" % timeit.timeit("inter_for(sets)",
"from __main__ import inter_for, sets", number=1000)
print len(sets[0])
@smarnach
Copy link

Only noted now you commented on my gist yesterday -- I didn't even know this is possible. Using deepcopy() is definitely overkill here -- result = next(sets).copy() will do the trick.

@pzelnip
Copy link
Author

pzelnip commented Feb 29, 2012

Yeah I suppose that's true, since none of the elements of the set are modified (so no need to copy them all). Added this to the snippet, when running it was almost identical to the union() version give or take a couple hundredths of a second.

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