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
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/ |
participants (2)
-
alan.gauld@bt.com -
Seth David Schoen