On 22/11/05, Alan Gauld <[EMAIL PROTECTED]> wrote: > But in the general case can you do the same job as > reduce in a list comprehension? ie apply an operation > to the first two elements of a sequence and replace > them with the result, then repeat until the list becomes > a single value?
Well ... probably not. I may have been exaggerating ever-so-slightly in my praise of list comprehensions :-) Although you may be able to cheat: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 (but I'm pretty certain that this "feature" is on Guido's hitlist) Hmm... >>> def f(x, y): ... return x + y ... >>> arr = range(10) >>> sum(arr) # Our target 45 >>> tmp = [0] >>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, y)) or True][-1] 45 Let's try some more... >>> def f(x, y): ... return x*y ... >>> arr = range(1, 10) # Don't want to include 0! >>> reduce(f, arr) # Our target 362880 >>> tmp = [1] >>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, y)) or True][-1] 362880 >>> print 'Magic!' Magic! -- John. _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
