[Edu-sig] RE: [Tutor] style question
Seth David Schoen
schoen@loyalty.org
Thu, 21 Feb 2002 22:46:11 -0800
alan.gauld@bt.com writes:
> > some feedbakc. Let's say you have a task of finding out how many of 5
> > positive integer numbers (a-e) are even. Which (if either) of the two
> > codes would be preferred:
> >
> > # {option A}
> > odd=a%2+b%2+c%2+d%2+e%2
> > even=5-odd
>
> Yech! I don't like this under any circumstance.
> If I really wanted to do it in two lines I'd try something like:
>
> >>> count = 0
> >>> L = [a,b,c,d,e]
> >>> for n in L:
> if n%2: count += 1
>
> > # {option B}
> > if a%2==0:
> > even = even + 1
> > if b%2==0:
> > even = even + 1
> > if c%2==0:
> > even = even + 1
> > if d%2==0:
> > even = even + 1
> > if e%2==0:
> > even = even + 1
I like lambda and filter a lot:
L = [a,b,c,d,e]
even = len(L) - len(filter(lambda x: x%2, L))
Some people prefer "x&1" instead of "x%2". "~x&1" is probably the
shortest Python expression for "x is even", so you could write
even = len(filter(lambda x: ~x&1, L))
--
Seth David Schoen <schoen@loyalty.org> | Reading is a right, not a feature!
http://www.loyalty.org/~schoen/ | -- Kathryn Myronuk
http://vitanuova.loyalty.org/ |