indexed() generator
Raymond Hettinger
othello at javanet.com
Fri Jan 25 20:50:31 CET 2002
"Michael Hudson" <mwh at python.net> wrote in message
news:uk7u6fj5i.fsf at python.net...
> Jonathan Hogg <jonathan at onegoodidea.com> writes:
>
> > I'm aware that many people have no use for the functional-style
> > definitions like 'map' and 'reduce'. I personally think they are
> > tremendously useful. [But then I programmed in Haskell for years.]
>
> map() I tolerate, even like. I really do think reduce() is useless,
> in the sense that any use of it can be more clearly and more
> efficiently written using plainer Python. What do you use it for?
I think 'reduce' is great and use it all the time:
>From a multi-dimensional table class:
def flatten( self ):
if self.dim == 1: return self
return reduce( lambda cum, e: e.flatten().concat(cum), self, [] )
def prod( self ): return reduce(operator.mul, self.flatten(), 1.0)
def sum( self ): return reduce(operator.add, self.flatten(), 0.0)
>From a vector class:
def dot( self, otherVec ): return reduce(operator.add,
map(operator.mul, self, otherVec), 0.0)
def polyval( self, x ):
"Vec([6,3,4]).polyval(5) evaluates to 6*x**2 + 3*x + 4 at x=5 using
Horner's method"
return reduce( lambda cum,c: cum*x+c, self, 0.0 )
>From a symbolic algebra package:
sumOfConsts = reduce( lambda x,y: x.value+y.value, constants,
Constant(0) )
>From a function computing continuted fractions:
reduce( lambda x,y: y+1/(x+1), alist, 0.0 )
Raymond Hettinger
More information about the Python-list
mailing list