|
|||
|
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 |
|
|
||||
|
||||
|
|
![]() |
| Thread Tools | |
| Display Modes | |
|
|