LISTS: Extract every other element - SUMMARY

Mike Fletcher mfletch at tpresence.com
Fri Dec 17 13:55:43 EST 1999


One more, ever-so-slightly faster version...  Speed benefit above the
column-selection Numeric is pretty minor (~.44 (avg) down to .433), but if
you've got a need for speed, every few milliseconds counts :) .

def test4( data, step=2, offset=0):
	import Numeric
	return Numeric.array( data, Numeric.Int32 )[::2]

Enjoy,
Mike

-----Original Message-----
From: Randall Hopper [mailto:aa8vb at yahoo.com]
Sent: Friday, December 17, 1999 9:13 AM
To: Charles G Waldman; Mike Fletcher; Adrian Eyre
Cc: python-list at python.org
Subject: LISTS: Extract every other element - SUMMARY


     Thanks for the suggestions.  Many of these are really novel ideas I
hadn't thought of.

     I coded each of these up, working with the same list of 100,000
integers.  Here are the results.

     To my amazement, the simple for loop approach is pretty decent, as
Mike mentioned.  Numeric will get you a little improvement (30-35%) if you
use the shape-change column-selection approach Mike suggested.


  RESULTS:

                     Using range()                    Using xrange()
                 -----------------------------------------------------------
  APPROACH #1   |  100.00%  (2.13357 sec)    |     100.00%  (2.03318 sec)  *
  APPROACH #1b  |   96.91%  (2.0677 sec)     |      98.20%  (1.9965 sec)   *
  APPROACH #2   |  690.97%  (14.7423 sec)    |     719.24%  (14.6235 sec)  *
  APPROACH #3   |  121.29%  (2.58789 sec)    |     122.02%  (2.48094 sec)  *
  APPROACH #4   |  308.55%  (6.58309 sec)    |     323.81%  (6.58367 sec)
  APPROACH #4b  |  705.80%  (15.0587 sec)    |     740.94%  (15.0646 sec)
  APPROACH #5   |  104.58%  (2.23128 sec)    |     105.42%  (2.14335 sec)  *
  APPROACH #6   |   66.42%  (1.41702 sec)    |      70.39%  (1.43119 sec)

                                  * = uses range/xrange

 
----------------------------------------------------------------------------
-
  APPROACH KEY:

  APPROACH #1  - Original "for loop" implementation
  APPROACH #1b - #1 but use multiply rather than divide
  APPROACH #2  - filter( lambda a: a != None, 
                         map( even_select, lst, range(len(lst)) )
  APPROACH #3  - map( lambda x: lst[x], range(0, len(lst), 2) )
  APPROACH #4  - filter( on_off, lst ) , where on_off() funct alternates 1/0
  APPROACH #4b - filter( onoff(), lst ), where onoff() class instance alt's
1/0
  APPROACH #5  - a = Numeric.array( lst, 'O' )
                 lst2 = list( Numeric.take( a, range(0,len(a),2) ) )
  APPROACH #6  - data = Numeric.array( lst, Numeric.Int32 )
                 data.shape = ( -1, step )
                 lst2 = list( data[:,0] )
 
----------------------------------------------------------------------------
-

-- 
Randall Hopper
aa8vb at yahoo.com




More information about the Python-list mailing list