Last active
June 30, 2017 03:28
-
-
Save mondwan/dafa8dfcb598de52b75e1680a6ff5a73 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
B = [2, 4, 6, 8, 10] | |
setA = set(A) | |
setB = set(B) | |
# C = A ^ B | |
def doubleLoop(): | |
C = [a for a in A for b in B if a == b] | |
def doubleLoop2(): | |
C = [] | |
for a in A: | |
for b in B: | |
if a == b: | |
C.append(a) | |
def setAnd(): | |
C = sorted(setA.intersection(setB)) | |
def setAnd2(): | |
# No sort | |
C = setA.intersection(setB) | |
def setAnd3(): | |
# Inline construct | |
C = sorted(set(A).intersection(set(B))) | |
def setAnd4(): | |
# Inline construct and no sort | |
C = set(A).intersection(set(B)) | |
if __name__ == '__main__': | |
from timeit import timeit | |
print 'Double loop' | |
print timeit('doubleLoop()', setup='from __main__ import doubleLoop') | |
print 'Double loop2' | |
print timeit('doubleLoop2()', setup='from __main__ import doubleLoop2') | |
print 'Set AND' | |
print timeit('setAnd()', setup='from __main__ import setAnd') | |
print 'Set AND2' | |
print timeit('setAnd2()', setup='from __main__ import setAnd2') | |
print 'Set AND3' | |
print timeit('setAnd3()', setup='from __main__ import setAnd3') | |
print 'Set AND4' | |
print timeit('setAnd4()', setup='from __main__ import setAnd4') | |
# Double loop | |
# 1.4873290062 | |
# Double loop2 | |
# 1.70801305771 | |
# Set AND | |
# 0.525309085846 | |
# Set AND2 | |
# 0.199652194977 | |
# Set AND3 | |
# 0.982024908066 | |
# Set AND4 | |
# 0.657478094101 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment