[Tutor] reduce with comprehension
Alan Gauld
alan.gauld at freenet.co.uk
Fri Nov 25 00:18:10 CET 2005
> But in the general case can you do the same job as
> reduce in a list comprehension?
>>> def f(x, y):
... return x + y
...
>>> 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
...
>>> tmp = [1]
>>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, y)) or
>>> True][-1]
362880
OK, you've nearly convinced me that its possible but I think I still
prefer reduce()! :-)
Alan G.
More information about the Tutor
mailing list