[Tutor] reduce with comprehension

Nick Lunt nick at javacat.f2s.com
Thu Nov 24 23:15:26 CET 2005



> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On
> >>> 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!

LOL I feel like I've accidentally signed up for the perl-tutor list ;)
 


More information about the Tutor mailing list