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

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 20 Feb 2002 22:02:52 -0800 (PST)


On Wed, 20 Feb 2002, Kirby Urner wrote:

> At 12:10 AM 2/21/2002 +0100, Remco Gerlich wrote:
> >On  0, "Michael P. Reilly" <arcege@speakeasy.net> wrote:
> > > However, it is still a "bad idea" to add boolean values.
> >
> >However, a%2 isn't a boolean just because it's either 0 or 1. It's the
> >remainder if a is divided by 2. And the sum of those remainders is
> >obviously the number of nubmers that were odd.
> 
> In the example being criticized (mine), I was going
> a%2==1, getting a boolean to count evens, which is
> what we wanted to count, not the number of odds.
> 
> But the proposed alternative used the same boolean test, but filtered
> out the falses, counting the number of remainders.  What I'm not
> getting is why adding 1s is worse than filtering out 0s and counting
> how many are left.

[warning; code below contains Java.  Avert your eyes!  *grin*]


Certain languages have a specific 'boolean' type that is distinct from any
other values.  Let's look at the code again:

###
def check(testlist):
    return reduce(add,[i%2==0 for i in testlist])
###

I think Arcage's point was that the expression 'i % 2 == 0' is supposed to
be a "boolean", something that's either true or false.  We know that
Python gives back to us '1' if the expression is true, and '0' otherwise.  
However, not all programming languages work this way!


In many cases, 'true' and 'false' are not numeric.  Java, for example, is
very strict about forcing us to be mind-numbingly exact about things.  In
PseudoJava, the check() function might look something like this:

////// PseudoJava
static public int check(int[] testlist) {
    int sum = 0;
    for(int index = 0; index < testlist.length; i++) {
        if (i % 2 == 0) {
            sum = sum + 1;
        }
        // I'm somewhat exaggerating the boringness here.  We can
        // actually do something like:
        //     sum = sum + (i % 2 == 0 ? 1 : 0);
        // to convert the boolean back to an integer that's safe to
        // add.
    }
    return sum;
}
//////


The proposed alternative:

###
how_many_evens = len( filter(lambda i, i%2==0, testlist) )
###

avoids the issue altogether by not adding "booleans".


Personally, I think it's ok to add booleans; I feel it's fairly safe to
assme that equality testing returns an integer.


Hope this helps!