Trinary operator?
Andrew Dalke
dalke at dalkescientific.com
Fri Apr 19 13:15:32 EDT 2002
Dale Strickland-Clark:
>But several orders of magnitude more processing [to use a dictionary
>compared to an and/or solution]. Certainly not for tight, efficient loops.
Perhaps your intuition comes from C? That doesn't seem to be the
case for Python.
>>> def do_filter1(data):
... for x in data:
... v = x == 'm' and 'male' or 'female'
...
>>> def do_filter2(data):
... d = {"m": "male", "f": "female"}
... for x in data:
... v = d[x]
...
>>> def test_size(n):
... data = ["m", "f"] * n
... t1 = time.clock()
... do_filter1(data)
... t2 = time.clock()
... do_filter2(data)
... t3 = time.clock()
... print "and/or", t2-t1, "dict", t3-t2, "ratio", (t2-t1)/(t3-t2)
...
>>> import time
>>> test_size(10000)
and/or 0.04392 dict 0.02928 ratio 1.5
>>> test_size(100000)
and/or 0.437248 dict 0.298656 ratio 1.46405228758
>>> test_size(1000000)
and/or 4.379312 dict 3.004128 ratio 1.45776478233
>>>
Dictionary looks faster to me, in this small, tight loop.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list