From: Alessandro [AkiRoss] Re on 16 Jun 2010 06:46 On Jun 15, 2:37 pm, Peter Otten <__pete...(a)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
From: Lie Ryan on 16 Jun 2010 06:47 On 06/15/10 21:49, 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 solution: > >>>> s = 0 >>>> for i in range(1, 2011): > .... s += i**2 > .... if not (i+1)%5: > .... s -= 2*i**2 > .... if not i%5: > .... s -= 2*i**2 > .... >>>> print s > 536926141 Probably bending the rules a little bit: >>> sum(x**2 - 8*x - 20 for x in range(1, 2010, 5)) 536926141 another variation: >>> sum((x - 10) * (x + 2) for x in range(1, 2010, 5)) 536926141
From: Jussi Piitulainen on 16 Jun 2010 07:10 Lie Ryan writes: > On 06/15/10 21:49, 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) [...] > Probably bending the rules a little bit: > > >>> sum(x**2 - 8*x - 20 for x in range(1, 2010, 5)) > 536926141 > > another variation: > > >>> sum((x - 10) * (x + 2) for x in range(1, 2010, 5)) > 536926141 Gleefully bending the rules all the way: >>> 536926141 536926141 Cheers!
From: Stefan Behnel on 16 Jun 2010 07:24 Jussi Piitulainen, 16.06.2010 13:10: > Lie Ryan writes: > >> On 06/15/10 21:49, 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) > [...] >> Probably bending the rules a little bit: >> >>>>> sum(x**2 - 8*x - 20 for x in range(1, 2010, 5)) >> 536926141 >> >> another variation: >> >>>>> sum((x - 10) * (x + 2) for x in range(1, 2010, 5)) >> 536926141 > > Gleefully bending the rules all the way: > >>>> 536926141 > 536926141 Timeit: 100000000 loops, best of 3: 0.0148 usec per loop Certainly the fastest solution so far. Stefan
From: Richard Brodie on 16 Jun 2010 08:41
"Lie Ryan" <lie.1296(a)gmail.com> wrote in message news:4c18ac33(a)dnews.tpgi.com.au... > Probably bending the rules a little bit: > >>>> sum(x**2 - 8*x - 20 for x in range(1, 2010, 5)) > 536926141 Or, letting Python do the algera for you: >>> from sympy import var, sum >>> dummy = var('j k') >>> k = (5 * j) + 1 >>> t = (k)**2 + (k + 1)**2 + (k + 2)**2 - (k + 3)**2 - (k + 4)**2 >>> sum(t, (j, 0, 401)) 536926141 |