map/filter/reduce/lambda opinions and background unscientific mini-survey
Dan Bishop
danb_83 at yahoo.com
Wed Jul 6 12:45:48 EDT 2005
Devan L wrote:
> > Here's a couple of examples from my own code:
> >
> > # from a Banzhaf Power Index calculator
> > # adds things that aren't numbers
> > return reduce(operator.add,
> > (VoteDistributionTable({0: 1, v: 1}) for v in electoral_votes))
>
> return sum([VoteDistributionTable({0:1, v:1} for v in
> electoral_votes],VoteDistributionTable({}))
> Any time you use operator.add, you can probably use
> sum(sequence,initialvalue)
Actually, it's
sum([VoteDistributionTable({0:1, v:1}) for v in electoral_votes],
VoteDistributionTable({0: 1}))
but you're right about being able to use sum here.
> > # from a custom numeric class
> > # converts a tuple of digits into a number
> > mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa)
>
> I'll admit I can't figure out a way to replace reduce without writing
> some ugly code here, but I doubt these sorts of things appear often.
Of the quarter-megabyte of my Python code currently on my hard drive, I
can find two reduces that can't be replaced by sum, product, any, or
all. The other one is
return reduce(lambda x, y: x << 1 | y, bits)
More information about the Python-list
mailing list