A curious bit of code...

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Feb 13 16:14:09 EST 2014


On 13/02/2014 21:01, Neil Cerutti wrote:
> On 2014-02-13, Zachary Ware <zachary.ware+pylist at gmail.com> wrote:
>> In a fit of curiosity, I did some timings:
>>
>> 'and'ed indexing:
>>
>> C:\tmp>py -m timeit -s "key = '<test>'" "key[0] == '<' and key[-1] == '>'"
>> 1000000 loops, best of 3: 0.35 usec per loop
>>
>> C:\tmp>py -m timeit -s "key = '<test'" "key[0] == '<' and key[-1] == '>'"
>> 1000000 loops, best of 3: 0.398 usec per loop
>>
>> C:\tmp>py -m timeit -s "key = 'test>'" "key[0] == '<' and key[-1] == '>'"
>> 1000000 loops, best of 3: 0.188 usec per loop
>>
>> C:\tmp>py -m timeit -s "key = 'test'" "key[0] == '<' and key[-1] == '>'"
>> 10000000 loops, best of 3: 0.211 usec per loop
>>
>> C:\tmp>py -m timeit -s "key = ''" "key[0] == '<' and key[-1] == '>'"
>> Traceback (most recent call last):
>>    File "P:\Python34\lib\timeit.py", line 292, in main
>>      x = t.timeit(number)
>>    File "P:\Python34\lib\timeit.py", line 178, in timeit
>>      timing = self.inner(it, self.timer)
>>    File "<timeit-src>", line 6, in inner
>>      key[0] == '<' and key[-1] == '>'
>> IndexError: string index out of range
>
> The corrected version
>
> key and key[0] == '<' and key[-1] == '>'
>
> probably still wins the Pretty Unimportant Olympics.
>

Exactly how I'd write it.  To me it wins awards for being most boring 
and most obvious, obviously YMMV or we wouldn't be having this 
discussion.  Or argument.  Or contradiction :)

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com





More information about the Python-list mailing list