filter2
Delaney, Timothy
tdelaney at avaya.com
Thu Jun 13 22:53:03 EDT 2002
Designed to minimise external factors ...
def filter2 (test, l):
l1 = filter(test, l)
l2 = filter(lambda x, test=test: not test(x), l)
return l1, l2
def filter2t (test, l):
l1 = []
l2 = []
funcs = (l1.append, l2.append,)
map(lambda x: funcs[not test(x)](x), l)
return l1, l2
def filter2l (test, l):
l1 = []
l2 = []
funcs = [l1.append, l2.append,]
map(lambda x: funcs[not test(x)](x), l)
return l1, l2
def filter3t (test, l):
l1 = []
l2 = []
map(lambda x, test=test, funcs=(l1.append, l2.append,): funcs[not
test(x)](x), l)
return l1, l2
def filter3l (test, l):
l1 = []
l2 = []
map(lambda x, test=test, funcs=[l1.append, l2.append,]: funcs[not
test(x)](x), l)
return l1, l2
def test (x):
return not (x % 3)
def bench (f, r, l, t=test):
""""""
import time
clock = time.clock
try:
start = clock()
for i in r:
f(t, l)
t = clock() - start
print '%-10s %s' % (func.__name__ + ':', t,)
except NameError:
pass
r = range(1000)
l = range(1000)
filters = (filter2, filter2t, filter2l, filter3t, filter3l,)
for func in filters:
bench(func, r, l)
Python 1.5.2 ...
filter2: 5.0598633013
filter3t: 4.76191299505
filter3l: 4.37944378728
Python 2.2.1 ...
filter2: 5.40253108615
filter2t: 4.38322776899
filter2l: 4.40173851257
filter3t: 4.32153526376
filter3l: 4.26489291133
filter3l is the fastest in both cases. filter3l also has the advantage of
working in any Python version.
Note: in filter3t and filter3l I original defined a nested function, but
this made the function perform worse than filter2t and filter2l - presumably
due to needing to bind the function name, then look it up for the map call.
Tim Delaney
More information about the Python-list
mailing list