[Tutor] Re: style question

Christopher Smith csmith@blakeschool.org
Thu, 21 Feb 2002 12:41:17 -0600


Thanks for the feedback on this question:

I think it raised a couple good points:

1) avoid code with repeated lines that differ by a small amount; slight
differences that might actually be an error will be easily missed.

2) don't rely on logical values as part of a calculation.  Whereas

def count_evens(list):
  from operator import add
  return reduce(add, [i%2==0 for i in list])

is relying on a logical value, the following does not.  The following
relies on the modulus operator returning the remainder after division by 2
which can only be 0 or 1 (unless it's been redefined for a new class of
variables, but hopefully you would know that and not do it this way).  If
n%2 is 1 then n is odd.

def count_odds(list):
  from operator import add
  return reduce(add, [i%2 for i in list])


The following puts items into the result list only if they are even and
again is not using the logical value as part of the arithmetic so it is ok.

def count_evens(list):
  return len([i for i in list if i%2==0])

But this is even a little less transparent than just clearly indicating an
incremented count variable as suggested by Alan (I changed the "count" to
"odds" to indicate what is being counted):
>
>>>> 
odds
> = 0
>>>> L = [a,b,c,d,e]
>>>> for n in L:
>      if n%2: 
odds
> += 1

/c