filter2

Michael Hudson mwh at python.net
Thu Jun 13 12:29:08 EDT 2002


Jeff Epler <jepler at unpythonic.net> writes:

> On Thu, Jun 13, 2002 at 03:00:28PM +0000, Michael Hudson wrote:
> > Write it in Python.  Particularly if test is expensive the loop
> > overhead will disappear into the noise.
> > 
> > (with-seriousness-level :low
> >   If you insist on C loops, there's always:
> > 
> >       lt = map(lambda x:(test(x), x), alist)
> >       l1 = filter(lambda (x,y):x, lt)
> >       l2 = filter(lambda (x,y):not x, lt)
> > 
> >   But I doubt you need me to tell you why this solution sucks.)
> 
> If you're benchmarking, try a solution like this in the mix.  It only
> has one map/filter call, not map+2*filter. (uses nested scopes and the
> new bool() builtin, but this can be avoided if necessary)
> 
> def filter2(test, list):
>     l1 = []
>     l2 = []
>     funcs = [l2.append, l1.append]
>     map(lambda x: funcs[bool(test(x))](x), list)
>     return l1, l2
> 
> >>> print filter2(lambda x: x%3==0, range(16))
> ([0, 3, 6, 9, 12, 15], [1, 2, 4, 5, 7, 8, 10, 11, 13, 14])

Hey, that's pretty neat!  Still three function calls per element,
though.  Well, four including bool, but that could be gotten rid of by
gross hacks (e.g. not not test(x)).

Cheers,
M.

-- 
  Worryingly, DEFUN appears to be a function that removes all the
  fun from something: after using it all your code is converted 
  to C++.                              -- Tim Bradshaw, comp.lang.lisp



More information about the Python-list mailing list