Go Back   Rhinocerus > Newsgroup > Newsgroup comp.lang.python

Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old 08-16-2012, 02:31 PM
Virgil Stokes
Guest
 
Posts: n/a
Default Re: Strange behavior

On 16-Aug-2012 15:02, Peter Otten wrote:
> Virgil Stokes wrote:
>
>>>> def testFunc(startingList):
>>>> xOnlyList = []; j = -1
>>>> for xl in startingList:
>>>> if (xl[0] == 'x'):
>>> That's going to fail in the starting list contains an empty string. Use
>>> xl.startswith('x') instead.

>> Yes, but this was by design (tacitly assumed that startingList was both a
>> list and non-empty).

> You missunderstood it will fail if the list contains an empty string, not if
> the list itself is empty:
>
>>>> words = ["alpha", "", "xgamma"]
>>>> [word for word in words if word[0] == "x"]

> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> IndexError: string index out of range
>
> The startswith() version:
>
>>>> [word for word in words if word.startswith("x")]

> ['xgamma']
>
> Also possible:
>
>>>> [word for word in words if word[:1] == "x"]

> ['xgamma']
>
>> def testFunc1(startingList):
>> '''
>> Algorithm-1
>> Note:
>> One should check for an empty startingList before
>> calling testFunc1 -- If this possibility exists!
>> '''
>> return([x for x in startingList if x[0] == 'x'],
>> [x for x in startingList if x[0] != 'x'])
>>
>>
>> I would be interested in seeing code that is faster than algorithm-1

> In pure Python? Perhaps the messy variant:
>
> def test_func(words):
> nox = []
> append = nox.append
> withx = [x for x in words if x[0] == 'x' or append(x)]
> return withx, nox
>
>

Very nice Peter,

Here are the new results for timing with your method added (algorithm-3).

Method
average (sd) time in seconds
algorithm-1 (list comprehension)
0.11774 (0.002968)
algorithm-2 (S. D'Aprano)
0.17573 (0.003385)
algorithm-2A (modified S. D'Aprano)
0.18116 (0.003081)
algorithm-3 (improved list comprehension)
0.06639 (0.001728)


Algorithm-3 is 43% faster than algorithm-1. Again, the code used to obtain
these results is attached.

Thanks Peter for your contribution

Reply With Quote
Alt Today
Advertising
 
and become member of Rhinocerus
Standard Sponsored Links

Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off




All times are GMT. The time now is 05:29 AM.


Copyright ©2009

LinkBacks Enabled by vBSEO 3.3.0 RC2 © 2009, Crawlability, Inc.