[Edu-sig] RE: [Tutor] style question

alan.gauld@bt.com alan.gauld@bt.com
Thu, 21 Feb 2002 11:45:41 -0000


> 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

This is the same as above but writing the loop longhand...

> Is option A guilty of relying on the "side effect" of mod 2 
> being a 1 or zero or is this a desireable/understandable 
> use of this function's return

It's an acceptable use but just plain obtuse. The minor gain 
in performance over the loop doesn't justify the loss of 
readability IMHO.

Alan g