Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #27166

Re: Strange behavior

Date 2012-08-16 16:31 +0200
From Virgil Stokes <vs@it.uu.se>
Subject Re: Strange behavior
Newsgroups comp.lang.python
Message-ID <mailman.3364.1345128356.4697.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Strange behavior Virgil Stokes <vs@it.uu.se> - 2012-08-16 16:31 +0200

csiph-web