Re: pythonize this!

2010-06-16 Thread Alessandro [AkiRoss] Re
On Jun 15, 1:49 pm, superpollo  wrote:
> goal (from e.c.m.): evaluate
> 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three
> consecutive + must be followed by two - (^ meaning ** in this context)


My functional approach :)

from operator import add
from functools import reduce

def square(l):
  return (v**2 for v in l)

def sign(l, s):
  i = 0
  for v in l:
yield s[i % len(s)] * v
i += 1

print reduce(add, sign(square(xrange(1, 2011)), [1, 1, 1, -1, -1]))

(536926141)

~Aki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pythonize this!

2010-06-16 Thread Alessandro [AkiRoss] Re
On Jun 15, 2:37 pm, Peter Otten <__pete...@web.de> wrote:
> >>> from itertools import cycle, izip
> >>> sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011)))

Wow!! :D
I didn't knew cycle, great! With that i can reduce my solution (which
isn't still elegant as your) to:

print reduce(add,imap(mul, cycle([1, 1, 1, -1, -1]), (v**2 for v in
xrange(1, 2011

(536926141)
~Aki
-- 
http://mail.python.org/mailman/listinfo/python-list