Python Tutorial Was: Guido's regrets: filter and map
Lulu of the Lotus-Eaters
mertz at gnosis.cx
Wed Nov 27 18:07:42 EST 2002
"Anders J. Munch" <andersjm at dancontrol.dk> wrote previously:
|> reduce = lambda func, seq, init=None:\
|> [(l.append(func(l[i],seq[i])),l[-1])
|> for l in [[init or seq[0]]]
|> for i in range(len(seq))][-1][1]
|
|Needs more "improvement" ;-)
|>>> reduce(operator.add, [1,2,3])
|6
|>>> lulu_reduce(operator.add, [1,2,3])
|7
Yep. I got the stuff with optional 'init' wrong. Here's a version I am
more confident about:
reduce_ = lambda func, seq, init=None:\
[(l.append(func(l[-1],e)),l[-1])
for l in [init is None and seq[:1] or [init]]
for e in seq[init is None:]][-1][1]
Bengt Richter proposed a slightly longer version, but it required an
external 'id' variable. I like mine better, especially now that I got
rid of the 'i' numeric indexing, and just iterate directly over a slice
of 'seq'.
>>> from sick import reduce_
>>> from operator import add
>>> reduce(add, range(5)), reduce_(add, range(5))
(10, 10)
>>> reduce(add, range(1,5)), reduce_(add, range(1,5))
(10, 10)
>>> reduce(add, range(5), 0), reduce_(add, range(5), 0)
(10, 10)
>>> reduce(add, range(1,5), 0), reduce_(add, range(1,5), 0)
(10, 10)
>>> reduce(add, range(5), 10), reduce_(add, range(5), 10)
(20, 20)
>>> reduce(add, range(1,5), 10), reduce_(add, range(1,5), 10)
(20, 20)
Yours, Lulu...
--
mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i
gnosis _/_/ Postmodern Enterprises _/_/ s r
.cx _/_/ MAKERS OF CHAOS.... _/_/ i u
_/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s
More information about the Python-list
mailing list